Arrayliteralconvertible: Just a Normal Protocol

ArrayLiteralConvertible: Just a normal protocol?

Generally, literals are a purely compile-time artifact. They can be used to produce an object initialized from that literal, but once the compilation phase is over, nobody knows that something was a literal.

This suggests that any support for the protocols below needs to be built into the compiler itself:

  • ArrayLiteralConvertible
  • BooleanLiteralConvertible
  • DictionaryLiteralConvertible
  • ExtendedGraphemeClusterLiteralConvertible
  • FloatLiteralConvertible
  • NilLiteralConvertible
  • IntegerLiteralConvertible
  • StringLiteralConvertible
  • StringInterpolationConvertible
  • UnicodeScalarLiteralConvertible

The compiler would not take your own protocol as a replacement of any of the above.

Full list of fundamental Swift types

Update

As of Xcode 9.4 (which includes Swift 4.1.2), you can make Xcode show you the declarations of its standard library by entering import Swift, selecting the word Swift, and then jumping to its definition.

Xcode 9.4 demo

I copied the contents of that generated file and ran this command:

pbpaste | egrep '^public (struct|protocol|class|enum)' > /tmp/swifttypes

Here's the result:

public struct AnyBidirectionalCollection<Element> {
public struct AnyCollection<Element> {
public struct AnyHashable {
public struct AnyIndex {
public struct AnyIterator<Element> {
public class AnyKeyPath : Hashable, _AppendKeyPath {
public struct AnyRandomAccessCollection<Element> {
public struct AnySequence<Element> {
public struct Array<Element> {
public struct ArraySlice<Element> {
public struct AutoreleasingUnsafeMutablePointer<Pointee> {
public protocol BidirectionalCollection : Collection where Self.Indices : BidirectionalCollection, Self.SubSequence : BidirectionalCollection {
public protocol BinaryFloatingPoint : ExpressibleByFloatLiteral, FloatingPoint {
public protocol BinaryInteger : CustomStringConvertible, Hashable, Numeric, Strideable where Self.Magnitude : BinaryInteger, Self.Magnitude == Self.Magnitude.Magnitude {
public struct Bool {
public struct CVaListPointer {
public protocol CVarArg {
public struct Character {
public struct ClosedRange<Bound> where Bound : Comparable {
public struct ClosedRangeIndex<Bound> where Bound : Strideable, Bound.Stride : SignedInteger {
public protocol CodingKey : CustomDebugStringConvertible, CustomStringConvertible {
public struct CodingUserInfoKey : RawRepresentable, Equatable, Hashable {
public protocol Collection : Sequence where Self.SubSequence : Collection {
public struct CollectionOfOne<Element> {
public enum CommandLine {
public protocol Comparable : Equatable {
public struct ContiguousArray<Element> {
public struct CountableClosedRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger {
public struct CountablePartialRangeFrom<Bound> where Bound : Strideable, Bound.Stride : SignedInteger {
public struct CountableRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger {
public protocol CustomDebugStringConvertible {
public protocol CustomLeafReflectable : CustomReflectable {
public protocol CustomPlaygroundDisplayConvertible {
public protocol CustomPlaygroundQuickLookable {
public protocol CustomReflectable {
public protocol CustomStringConvertible {
public protocol Decodable {
public protocol Decoder {
public enum DecodingError : Error {
public struct DefaultIndices<Elements> where Elements : Collection {
public struct Dictionary<Key, Value> where Key : Hashable {
public struct DictionaryIterator<Key, Value> : IteratorProtocol where Key : Hashable {
public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral {
public struct Double {
public struct EmptyCollection<Element> {
public struct EmptyIterator<Element> {
public protocol Encodable {
public protocol Encoder {
public enum EncodingError : Error {
public struct EnumeratedIterator<Base> where Base : IteratorProtocol {
public struct EnumeratedSequence<Base> where Base : Sequence {
public protocol Equatable {
public protocol Error {
public protocol ExpressibleByArrayLiteral {
public protocol ExpressibleByBooleanLiteral {
public protocol ExpressibleByDictionaryLiteral {
public protocol ExpressibleByExtendedGraphemeClusterLiteral : ExpressibleByUnicodeScalarLiteral {
public protocol ExpressibleByFloatLiteral {
public protocol ExpressibleByIntegerLiteral {
public protocol ExpressibleByNilLiteral {
public protocol ExpressibleByStringLiteral : ExpressibleByExtendedGraphemeClusterLiteral {
public protocol ExpressibleByUnicodeScalarLiteral {
public protocol FixedWidthInteger : BinaryInteger, LosslessStringConvertible, _BitwiseOperations where Self.Magnitude : FixedWidthInteger {
public struct FlattenBidirectionalCollection<Base> : BidirectionalCollection where Base : BidirectionalCollection, Base.Element : BidirectionalCollection {
public struct FlattenBidirectionalCollectionIndex<BaseElements> where BaseElements : BidirectionalCollection, BaseElements.Element : BidirectionalCollection {
public struct FlattenCollection<Base> : Collection where Base : Collection, Base.Element : Collection {
public struct FlattenCollectionIndex<BaseElements> where BaseElements : Collection, BaseElements.Element : Collection {
public struct FlattenIterator<Base> : IteratorProtocol, Sequence where Base : IteratorProtocol, Base.Element : Sequence {
public struct FlattenSequence<Base> : Sequence where Base : Sequence, Base.Element : Sequence {
public struct Float {
public struct Float80 {
public protocol FloatingPoint : Hashable, SignedNumeric, Strideable {
public enum FloatingPointClassification {
public enum FloatingPointRoundingRule {
public enum FloatingPointSign : Int {
public protocol Hashable : Equatable {
public enum ImplicitlyUnwrappedOptional<Wrapped> : ExpressibleByNilLiteral {
public struct IndexingIterator<Elements> where Elements : Collection {
public struct Int : FixedWidthInteger, SignedInteger {
public struct Int16 : FixedWidthInteger, SignedInteger {
public struct Int32 : FixedWidthInteger, SignedInteger {
public struct Int64 : FixedWidthInteger, SignedInteger {
public struct Int8 : FixedWidthInteger, SignedInteger {
public struct IteratorOverOne<Element> {
public protocol IteratorProtocol {
public struct IteratorSequence<Base> where Base : IteratorProtocol {
public struct JoinedIterator<Base> : IteratorProtocol where Base : IteratorProtocol, Base.Element : Sequence {
public struct JoinedSequence<Base> : Sequence where Base : Sequence, Base.Element : Sequence {
public class KeyPath<Root, Value> : PartialKeyPath<Root> {
public struct KeyedDecodingContainer<K> : KeyedDecodingContainerProtocol where K : CodingKey {
public protocol KeyedDecodingContainerProtocol {
public struct KeyedEncodingContainer<K> : KeyedEncodingContainerProtocol where K : CodingKey {
public protocol KeyedEncodingContainerProtocol {
public struct LazyCollection<Base> : LazyCollectionProtocol where Base : Collection {
public protocol LazyCollectionProtocol : Collection, LazySequenceProtocol where Self.Elements : Collection {
public struct LazyDropWhileBidirectionalCollection<Base> : LazyCollectionProtocol, BidirectionalCollection where Base : BidirectionalCollection {
public struct LazyDropWhileCollection<Base> : LazyCollectionProtocol, Collection where Base : Collection {
public struct LazyDropWhileIndex<Base> : Comparable where Base : Collection {
public struct LazyDropWhileIterator<Base> : IteratorProtocol, Sequence where Base : IteratorProtocol {
public struct LazyDropWhileSequence<Base> : LazySequenceProtocol where Base : Sequence {
public struct LazyFilterCollection<Base> where Base : Collection {
public struct LazyFilterIterator<Base> : IteratorProtocol, Sequence where Base : IteratorProtocol {
public struct LazyFilterSequence<Base> : LazySequenceProtocol where Base : Sequence {
public struct LazyMapCollection<Base, Element> : LazyCollectionProtocol, Collection where Base : Collection {
public struct LazyMapIterator<Base, Element> : IteratorProtocol, Sequence where Base : IteratorProtocol {
public struct LazyMapSequence<Base, Element> : LazySequenceProtocol where Base : Sequence {
public struct LazyPrefixWhileBidirectionalCollection<Base> : LazyCollectionProtocol, BidirectionalCollection where Base : BidirectionalCollection {
public struct LazyPrefixWhileCollection<Base> : LazyCollectionProtocol, Collection where Base : Collection {
public struct LazyPrefixWhileIndex<Base> : Comparable where Base : Collection {
public struct LazyPrefixWhileIterator<Base> : IteratorProtocol, Sequence where Base : IteratorProtocol {
public struct LazyPrefixWhileSequence<Base> : LazySequenceProtocol where Base : Sequence {
public struct LazySequence<Base> : LazySequenceProtocol, _SequenceWrapper where Base : Sequence {
public protocol LazySequenceProtocol : Sequence {
public protocol LosslessStringConvertible : CustomStringConvertible {
public struct ManagedBufferPointer<Header, Element> : Equatable {
public enum MemoryLayout<T> {
public struct Mirror {
public protocol MirrorPath {
public protocol MutableCollection : Collection where Self.SubSequence : MutableCollection {
public enum Never {
public protocol Numeric : Equatable, ExpressibleByIntegerLiteral {
public struct ObjectIdentifier {
public struct OpaquePointer {
public protocol OptionSet : RawRepresentable, SetAlgebra {
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
public class PartialKeyPath<Root> : AnyKeyPath {
public struct PartialRangeFrom<Bound> where Bound : Comparable {
public struct PartialRangeThrough<Bound> where Bound : Comparable {
public struct PartialRangeUpTo<Bound> where Bound : Comparable {
public enum PlaygroundQuickLook {
public protocol RandomAccessCollection : BidirectionalCollection where Self.Indices : RandomAccessCollection, Self.SubSequence : RandomAccessCollection {
public struct Range<Bound> where Bound : Comparable {
public protocol RangeExpression {
public protocol RangeReplaceableCollection : Collection where Self.SubSequence : RangeReplaceableCollection {
public protocol RawRepresentable {
public class ReferenceWritableKeyPath<Root, Value> : WritableKeyPath<Root, Value> {
public struct Repeated<Element> {
public struct ReversedCollection<Base> where Base : BidirectionalCollection {
public struct ReversedIndex<Base> : Comparable where Base : Collection {
public protocol Sequence {
public struct Set<Element> where Element : Hashable {
public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral {
public struct SetIterator<Element> : IteratorProtocol where Element : Hashable {
public protocol SignedInteger : BinaryInteger, SignedNumeric {
public protocol SignedNumeric : Numeric {
public protocol SingleValueDecodingContainer {
public protocol SingleValueEncodingContainer {
public struct Slice<Base> where Base : Collection {
public struct StaticString : ExpressibleByUnicodeScalarLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringLiteral, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public struct StrideThrough<Element> where Element : Strideable {
public struct StrideThroughIterator<Element> where Element : Strideable {
public struct StrideTo<Element> where Element : Strideable {
public struct StrideToIterator<Element> where Element : Strideable {
public protocol Strideable : Comparable {
public struct String {
public protocol StringProtocol : BidirectionalCollection, Comparable, ExpressibleByStringLiteral, Hashable, LosslessStringConvertible, TextOutputStream, TextOutputStreamable where Self.Element == Character, Self.SubSequence : StringProtocol {
public struct Substring : StringProtocol {
public protocol TextOutputStream {
public protocol TextOutputStreamable {
public struct UInt : FixedWidthInteger, UnsignedInteger {
public struct UInt16 : FixedWidthInteger, UnsignedInteger {
public struct UInt32 : FixedWidthInteger, UnsignedInteger {
public struct UInt64 : FixedWidthInteger, UnsignedInteger {
public struct UInt8 : FixedWidthInteger, UnsignedInteger {
public enum UnboundedRange_ {
public struct UnfoldSequence<Element, State> : Sequence, IteratorProtocol {
public enum Unicode {
public protocol UnicodeCodec : _UnicodeEncoding {
public enum UnicodeDecodingResult : Equatable {
public protocol UnkeyedDecodingContainer {
public protocol UnkeyedEncodingContainer {
public struct Unmanaged<Instance> where Instance : AnyObject {
public struct UnsafeBufferPointer<Element> : Collection, RandomAccessCollection {
public struct UnsafeBufferPointerIterator<Element> : IteratorProtocol, Sequence {
public struct UnsafeMutableBufferPointer<Element> : MutableCollection, RandomAccessCollection {
public struct UnsafeMutablePointer<Pointee> {
public struct UnsafeMutableRawBufferPointer {
public struct UnsafeMutableRawPointer {
public struct UnsafePointer<Pointee> {
public struct UnsafeRawBufferPointer {
public struct UnsafeRawPointer {
public protocol UnsignedInteger : BinaryInteger {
public class WritableKeyPath<Root, Value> : KeyPath<Root, Value> {
public struct Zip2Iterator<Iterator1, Iterator2> where Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol {
public struct Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence {
public protocol _AppendKeyPath {
public protocol _SequenceWrapper : Sequence {

Original

This is one of those areas where the Swift documentation is currently woeful.

Anyway, you can find the complete Swift built-in API by creating a Swift source file or playground, typing in any built-in type (or function), and then command-click it:

getting to swift API

This takes you to a generated Swift source file (it doesn't exist in the Xcode bundle) that declares the entire built-in Swift API. You can browse it to find all the built-in types. Each of types you mentioned (even Array and Dictionary) is declared as a struct, typically with a bunch of extensions. There are lots more built-in struct types, and bunch of protocol and class types too.

Piping that file through egrep '^(struct|protocol|class) finds these built-in types:

protocol AbsoluteValuable : SignedNumberType {
protocol AnyObject {
struct Array<T> : MutableCollectionType, Sliceable {
protocol ArrayBoundType {
protocol ArrayLiteralConvertible {
struct AssertString : AssertStringType, StringInterpolationConvertible {
protocol AssertStringType : ExtendedGraphemeClusterLiteralConvertible, StringLiteralConvertible {
struct AutoreleasingUnsafeMutablePointer<T> : Equatable, NilLiteralConvertible {
protocol BidirectionalIndexType : ForwardIndexType, _BidirectionalIndexType {
struct BidirectionalReverseView<T : CollectionType where T.Index : BidirectionalIndexType> : CollectionType {
protocol BitwiseOperationsType {
struct Bool {
protocol BooleanLiteralConvertible {
protocol BooleanType {
struct CFunctionPointer<T> : Equatable, Hashable, NilLiteralConvertible {
struct COpaquePointer : Equatable, Hashable, NilLiteralConvertible {
struct CVaListPointer {
protocol CVarArgType {
protocol CharacterLiteralConvertible {
struct ClosedInterval<T : Comparable> : IntervalType, Equatable, Printable, DebugPrintable, Reflectable {
struct CollectionOfOne<T> : CollectionType {
protocol CollectionType : _CollectionType, SequenceType {
protocol Comparable : _Comparable, Equatable {
struct ContiguousArray<T> : MutableCollectionType, Sliceable {
protocol DebugPrintable {
struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible {
struct DictionaryGenerator<Key : Hashable, Value> : GeneratorType {
struct DictionaryIndex<Key : Hashable, Value> : BidirectionalIndexType, Comparable {
protocol DictionaryLiteralConvertible {
struct Double {
struct EmptyCollection<T> : CollectionType {
struct EmptyGenerator<T> : GeneratorType, SequenceType {
struct EnumerateGenerator<Base : GeneratorType> : GeneratorType, SequenceType {
protocol Equatable {
protocol ExtendedGraphemeClusterLiteralConvertible {
protocol ExtensibleCollectionType : _ExtensibleCollectionType {
struct FilterCollectionView<Base : CollectionType> : CollectionType {
struct FilterCollectionViewIndex<Base : CollectionType> : ForwardIndexType {
struct FilterGenerator<Base : GeneratorType> : GeneratorType, SequenceType {
struct FilterSequenceView<Base : SequenceType> : SequenceType {
struct Float {
struct Float80 {
protocol FloatLiteralConvertible {
protocol FloatingPointType : Strideable {
protocol ForwardIndexType : _ForwardIndexType {
struct GeneratorOf<T> : GeneratorType, SequenceType {
struct GeneratorOfOne<T> : GeneratorType, SequenceType {
struct GeneratorSequence<G : GeneratorType> : GeneratorType, SequenceType {
protocol GeneratorType {
struct HalfOpenInterval<T : Comparable> : IntervalType, Equatable, Printable, DebugPrintable, Reflectable {
protocol Hashable : Equatable {
struct HeapBuffer<Value, Element> : Equatable {
class HeapBufferStorage<Value, Element> : HeapBufferStorageBase {
class HeapBufferStorageBase {
struct IndexingGenerator<C : _CollectionType> : GeneratorType, SequenceType {
struct Int : SignedIntegerType {
struct Int16 : SignedIntegerType {
struct Int32 : SignedIntegerType {
struct Int64 : SignedIntegerType {
struct Int8 : SignedIntegerType {
protocol IntegerArithmeticType : _IntegerArithmeticType, Comparable {
protocol IntegerLiteralConvertible {
protocol IntegerType : _IntegerType, RandomAccessIndexType {
protocol IntervalType {
struct LazyBidirectionalCollection<S : CollectionType where S.Index : BidirectionalIndexType> : CollectionType {
struct LazyForwardCollection<S : CollectionType where S.Index : ForwardIndexType> : CollectionType {
struct LazyRandomAccessCollection<S : CollectionType where S.Index : RandomAccessIndexType> : CollectionType {
struct LazySequence<S : SequenceType> : SequenceType {
struct MapCollectionView<Base : CollectionType, T> : CollectionType {
struct MapSequenceGenerator<Base : GeneratorType, T> : GeneratorType, SequenceType {
struct MapSequenceView<Base : SequenceType, T> : SequenceType {
protocol MirrorType {
protocol MutableCollectionType : CollectionType {
protocol MutableSliceable : Sliceable, MutableCollectionType {
protocol NilLiteralConvertible {
struct ObjectIdentifier : Hashable {
struct OnHeap<T> {
protocol OutputStreamType {
struct PermutationGenerator<C : CollectionType, Indices : SequenceType where C.Index == C.Index> : GeneratorType, SequenceType {
protocol Printable {
protocol RandomAccessIndexType : BidirectionalIndexType, _RandomAccessIndexType {
struct RandomAccessReverseView<T : CollectionType where T.Index : RandomAccessIndexType> : CollectionType {
struct Range<T : ForwardIndexType> : Equatable, CollectionType, Printable, DebugPrintable {
struct RangeGenerator<T : ForwardIndexType> : GeneratorType, SequenceType {
protocol RangeReplaceableCollectionType : ExtensibleCollectionType {
struct RawByte {
protocol RawOptionSetType : _RawOptionSetType, BitwiseOperationsType, NilLiteralConvertible {
protocol RawRepresentable {
protocol Reflectable {
struct Repeat<T> : CollectionType {
struct ReverseBidirectionalIndex<I : BidirectionalIndexType> : BidirectionalIndexType {
struct ReverseRandomAccessIndex<I : RandomAccessIndexType> : RandomAccessIndexType {
struct SequenceOf<T> : SequenceType {
protocol SequenceType : _Sequence_Type {
protocol SignedIntegerType : _SignedIntegerType, IntegerType {
protocol SignedNumberType : _SignedNumberType {
struct SinkOf<T> : SinkType {
protocol SinkType {
struct Slice<T> : MutableCollectionType, Sliceable {
protocol Sliceable : _Sliceable {
struct StaticString : StaticStringType {
protocol StaticStringType : AssertStringType {
protocol Streamable {
struct StrideThrough<T : Strideable> : SequenceType {
struct StrideThroughGenerator<T : Strideable> : GeneratorType {
struct StrideTo<T : Strideable> : SequenceType {
struct StrideToGenerator<T : Strideable> : GeneratorType {
protocol Strideable : Comparable, _Strideable {
struct String {
protocol StringElementType {
protocol StringInterpolationConvertible {
protocol StringLiteralConvertible : ExtendedGraphemeClusterLiteralConvertible {
struct UInt : UnsignedIntegerType {
struct UInt16 : UnsignedIntegerType {
struct UInt32 : UnsignedIntegerType {
struct UInt64 : UnsignedIntegerType {
struct UInt8 : UnsignedIntegerType {
struct UTF16 : UnicodeCodecType {
struct UTF32 : UnicodeCodecType {
struct UTF8 : UnicodeCodecType {
protocol UnicodeCodecType {
struct UnicodeScalar : ExtendedGraphemeClusterLiteralConvertible {
struct Unmanaged<T> {
struct UnsafeBufferPointer<T> : CollectionType {
struct UnsafeBufferPointerGenerator<T> : GeneratorType, SequenceType {
struct UnsafeMutableBufferPointer<T> : MutableCollectionType {
struct UnsafeMutablePointer<T> : RandomAccessIndexType, Hashable, NilLiteralConvertible {
struct UnsafePointer<T> : RandomAccessIndexType, Hashable, NilLiteralConvertible {
protocol UnsignedIntegerType : _UnsignedIntegerType, IntegerType {
struct Zip2<S0 : SequenceType, S1 : SequenceType> : SequenceType {
struct ZipGenerator2<E0 : GeneratorType, E1 : GeneratorType> : GeneratorType {
protocol _ArrayBufferType : MutableCollectionType {
protocol _BidirectionalIndexType : _ForwardIndexType {
protocol _CocoaStringType {
protocol _CollectionType : _SequenceType {
protocol _Comparable {
protocol _ExtensibleCollectionType : CollectionType {
protocol _ForwardIndexType : _Incrementable {
protocol _Incrementable : Equatable {
protocol _IntegerArithmeticType {
protocol _IntegerType : IntegerLiteralConvertible, Printable, ArrayBoundType, Hashable, IntegerArithmeticType, BitwiseOperationsType, _Incrementable {
protocol _ObjectiveCBridgeable {
protocol _PrintableNSObjectType {
protocol _RandomAccessIndexType : _BidirectionalIndexType, Strideable {
protocol _RawOptionSetType : RawRepresentable, Equatable {
protocol _SequenceType {
protocol _Sequence_Type : _SequenceType {
protocol _SignedIntegerType : _IntegerType, SignedNumberType {
protocol _SignedNumberType : Comparable, IntegerLiteralConvertible {
protocol _Sliceable : CollectionType {
protocol _Strideable {
protocol _SwiftNSArrayRequiredOverridesType : _SwiftNSCopyingType, _SwiftNSFastEnumerationType {
protocol _SwiftNSCopyingType {
protocol _SwiftNSDictionaryRequiredOverridesType : _SwiftNSCopyingType, _SwiftNSFastEnumerationType {
protocol _SwiftNSEnumeratorType {
protocol _SwiftNSFastEnumerationType {
protocol _SwiftNSStringRequiredOverridesType : _SwiftNSCopyingType, _SwiftNSFastEnumerationType {
protocol _SwiftNSStringType : _SwiftNSStringRequiredOverridesType {
protocol _UnsignedIntegerType : _IntegerType {

Alternative to overloading the assignment operator in Swift

To make an assignment

let myScalarString: ScalarString = "hello"

work with a string literal on the right-hand side, it suffices
that you implement the StringLiteralConvertible for your type:

extension ScalarString : StringLiteralConvertible {

init(stringLiteral value: String) {
self.init(value)
}

init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}

init(unicodeScalarLiteral value: String) {
self.init(value)
}
}

However, this works only for string literals, not for arbitrary strings,
so this would not compile:

let str = "hello"
let yourScalarString: ScalarString = str

because (as you already noticed) you cannot overload the assignment
operator, and you would have to use your init method explicitly:

let yourScalarString = ScalarString(str)

In the same manner, you could create a value of your type
from a literal array of Unicode values

let myScalarString: ScalarString = [ 65, 66, 67 ]

by implementing the ArrayLiteralConvertible protocol:

extension ScalarString : ArrayLiteralConvertible {
init(arrayLiteral elements: UInt32...) {
self.init(elements)
}

}

Custom SceneKit Geometry in Swift on iOS not working but equivalent Objective C code does

Well, the two pieces of code doesn't translate exactly to one another. The int in C is not the same as Int in Swift. It's actually called CInt in Swift:

/// The C 'int' type.
typealias CInt = Int32

If you change both occurrences to use CInt instead, the error message that you previously got goes away (at least for me in an OS X Playground. However, it still doesn't render anything for me.

I don't think sizeofValue is used to return the size of an array. It looks to me like it's returning the size of the pointer:

let indexes: CInt[] = [0, 1, 2]
sizeofValue(indexes) // is 8
sizeof(CInt) // is 4
sizeof(CInt) * countElements(indexes) // is 12

// compare to other CInt[]
let empty: CInt[] = []
let large: CInt[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

sizeofValue(indexes) // is 8 (your array of indices again)
sizeofValue(empty) // is 8
sizeofValue(large) // is 8

So, for me the following code works (I've put the arguments on different lines to make it easier to point out my changes):

let src = SCNGeometrySource(vertices: &verts, count: 3)
let indexes: CInt[] = [0, 1, 2] // Changed to CInt

let dat = NSData(
bytes: indexes,
length: sizeof(CInt) * countElements(indexes) // Changed to size of CInt * count
)
let ele = SCNGeometryElement(
data: dat,
primitiveType: .Triangles,
primitiveCount: 1,
bytesPerIndex: sizeof(CInt) // Changed to CInt
)
let geo = SCNGeometry(sources: [src], elements: [ele])

let nd = SCNNode(geometry: geo)
scene.rootNode.addChildNode(nd)

With this result:

Sample Image

Circular dependencies between generic types (CollectionType and its Index/Generator, e.g.)

While Airspeed Velocity's answer applies to the most common cases, my question was asking specifically about the special case of generalizing CollectionType indexing in order to be able to share a single Index implementation for all thinkable kinds of binary trees (whose recursive nature makes it necessary to make use of a stack for index-based traversals (at least for trees without a parent pointer)), which requires the Index to be specialized on the actual BinaryTree, not the Element.

The way I solved this problem was to rename MyCollection to MyCollectionStorage, revoke its CollectionType conformity and wrap it with a struct that now takes its place as MyCollection and deals with conforming to CollectionType.

To make things a bit more "real" I will refer to:

  • MyCollection<E> as SortedSet<E>
  • MyCollectionStorage<E> as BinaryTree<E>
  • MyIndex<T> as BinaryTreeIndex<T>

So without further ado:

struct SortedSet<Element>: CollectionType {
typealias Tree = BinaryTree<Element>
typealias Index = BinaryTreeIndex<Tree>

subscript(i: Index) -> Element { … }

func generate() -> IndexingGenerator<SortedSet> {
return IndexingGenerator(self)
}
}

struct BinaryTree<Element>: BinaryTreeType {

}

struct BinaryTreeIndex<BinaryTree: BinaryTreeType>: BidirectionalIndexType {
func predecessor() -> BinaryTreeIndex { … }
func successor() -> BinaryTreeIndex { … }
}

This way the dependency graph turns from a directed cyclic graph into a directed acyclic graph.

What is the syntax for multidimensional array in Swift?

Yes, there is nothing built-in (as far as I know). You can define a custom class/struct (as in Most efficient way to access multi-dimensional arrays in Swift?
or How to Declare a Multidimensional Boolean array in Swift?) with a subscript operator, so that a[0,0] = 1 works.

Here is a mixture of those solutions, but as a
generic struct instead of class. I have also changed the order of
the rows and columns parameters because I find that more natural:

struct Array2D<T : IntegerLiteralConvertible > {
let rows : Int
let cols : Int
var matrix: [T]

init(rows : Int, cols : Int) {
self.rows = rows
self.cols = cols
matrix = Array(count : rows * cols, repeatedValue : 0)
}

subscript(row : Int, col : Int) -> T {
get { return matrix[cols * row + col] }
set { matrix[cols*row+col] = newValue }
}
}

I don't see how to create such a thing from a literal like
[2, 3 ;; -1, 0]. But you could initialize it from a nested array:

extension Array2D {

init(_ elements: [[T]]) {
let rows = elements.count
let cols = elements[0].count
self.init(rows: rows, cols: cols)
for i in 0 ..< rows {
assert(elements[i].count == cols, "Array must have same number of elements for each row")
self.matrix.replaceRange(cols * i ..< cols * (i+1), with: elements[i])
}
}
}

Example:



Related Topics



Leave a reply



Submit