Arrays of Generics in Swift

前端 未结 5 1202
有刺的猬
有刺的猬 2020-12-13 06:05

I\'ve been playing around with arrays of generic classes with different types. It\'s easiest to explain my problem with some sample code:

// Obviously a very         


        
5条回答
  •  无人及你
    2020-12-13 06:25

    I changed the array declaration to be an array of AnyObject so that filter, map and reduce could be used (and also added in a few more objects to check for).

    let containers: [AnyObject] = [Container(1, 2, 3), Container(1.0, 2.0, 3.0), "Hello", "World", 42]
    

    This will allow you to check for type in the array and filter before you loop through the array

    let strings = containers.filter({ return ($0 is String) })
    
    println(strings) // [Hello, World]
    
    for ints in containers.filter({ return ($0 is Int) }) {
        println("Int is \(foo)") // Int is 42
    }
    
    let ints = containers.filter({ return ($0 is Container) })
    // as this array is known to only contain Container instances, downcast and unwrap directly
    for i in ints as [Container] {
        // do stuff
        println(i.values) // [1, 2, 3]
    }
    

提交回复
热议问题