Type conversion when using protocol in Swift

后端 未结 2 1318
日久生厌
日久生厌 2020-11-30 15:33
protocol Test{

    var t: Int {set get}

}

struct A: Test{

    var t: Int

}

struct B: Test{

    var t: Int
    var s: String

}

let a = A(t: 1)
let b = B(t: 2         


        
2条回答
  •  长情又很酷
    2020-11-30 16:04

    You cannot convert an array wholesale like that. Use map:

    let f = e.map { $0 as Test } // f is now a [Test] array
    

提交回复
热议问题