Question on Generic Collections

Could someone help:


I am curious if Swift has a way to store collections of class types the way that .net does.


For example .NET has something called a List(). If I have a class A, I can create this


List<A> Col = new List<A>();


B test = new B();


// Then I can add object's of type A ie:

Col.Add(B);


I know Swift has array's of strings, int's etc but how do you group class types?


thanks


David.

Answered by OOPer in 62922022

If you want to store instances of a class or its descendents, Swift generics is similar to C# or Java.

class A {}
class B: A {}
var col: [A] = [] //[A] is exactly the same as Array<A>
var test = B()
// Then you can add object's of type A ie:
col.append(test)

(It's not a strong restriction, but you usually use lower camel case for properties and method names in Swift.)


ADDITION: as for now, in Swift 2 (or 2.1 beta) you cannot find much variety of collection types in Swift Standard Library.

Only three, Array, Dictionary and Set, all generic.

Accepted Answer

If you want to store instances of a class or its descendents, Swift generics is similar to C# or Java.

class A {}
class B: A {}
var col: [A] = [] //[A] is exactly the same as Array<A>
var test = B()
// Then you can add object's of type A ie:
col.append(test)

(It's not a strong restriction, but you usually use lower camel case for properties and method names in Swift.)


ADDITION: as for now, in Swift 2 (or 2.1 beta) you cannot find much variety of collection types in Swift Standard Library.

Only three, Array, Dictionary and Set, all generic.

C# has arrays for speed and Lists for flexibility. Swift does not bother with both. Use Swift's arrays where you would use System.Array or List. Using let will be more like Array; var, more like List.

I'm not familiar with .Net, but I believe you are asking whether you can store an array of types from which you can then instantiate those types. The answer is yes as follows:


class A {
  required init() {
  print("Making: \(self.dynamicType)")
  }
}

class B : A {
}

let tarr : [A.Type] = [A.self, B.self, B.self, A.self]
for AKind in tarr {
  let _ = AKind.init()
}

Thanks for the great information. That was exactly what I was wondering about.


Thank to all!

Question on Generic Collections
 
 
Q