向下转换多协议 Array<protocol<P1, P2>> 到 Array<P1>
Down casting multiple protocol Array<protocol<P1, P2>> to Array<P1>
所以我有两个数组
var arrayOne:Array<protocol<P1,P2>>
var arrayTwo:Array<P1>
其中 P1 和 P2 是协议。
问题是如何进行向下转型
arrayTwo = arrayOne as Array<P1>
我从Xcode得到的是:
Cannot convert value of type 'Array<protocol<P1, P2>>' to specified type 'Array<P1>'
您需要转换数组的元素,而不是数组本身。
arrayTwo = arrayOne.map { [=10=] as P1 }
或者如 MartinR 所说,甚至不需要转换元素。
arrayTwo = arrayOne.map { [=11=] }
protocol P1{}
struct A: P1{}
// everybody knows, that
let a = A()
// (1)
let p: P1 = a
// or (2)
let p1 = a as P1
let arr: Array<A> = []
// has type
print(arr.dynamicType) // Array<A>
// (3) the array is converted to different type here !!
let arr1: Array<P1> = arr.map{ [=10=] }
print(arr1.dynamicType) // Array<P1>
// arr and arr1 are differnet types!!!
// the elements of arr2 can be down casted as in (1) or (2)
// (3) is just an equivalent of
typealias U = P1
let arr3: Array<U> = arr.map { (element) -> U in
element as U
}
print(arr3.dynamicType) // Array<P1>
// the array must be converted, all the elements are down casted in arr3 from A to P1
// the compiler knows the type so ii do the job like in lines (1) or (2)
所以我有两个数组
var arrayOne:Array<protocol<P1,P2>>
var arrayTwo:Array<P1>
其中 P1 和 P2 是协议。
问题是如何进行向下转型
arrayTwo = arrayOne as Array<P1>
我从Xcode得到的是:
Cannot convert value of type 'Array<protocol<P1, P2>>' to specified type 'Array<P1>'
您需要转换数组的元素,而不是数组本身。
arrayTwo = arrayOne.map { [=10=] as P1 }
或者如 MartinR 所说,甚至不需要转换元素。
arrayTwo = arrayOne.map { [=11=] }
protocol P1{}
struct A: P1{}
// everybody knows, that
let a = A()
// (1)
let p: P1 = a
// or (2)
let p1 = a as P1
let arr: Array<A> = []
// has type
print(arr.dynamicType) // Array<A>
// (3) the array is converted to different type here !!
let arr1: Array<P1> = arr.map{ [=10=] }
print(arr1.dynamicType) // Array<P1>
// arr and arr1 are differnet types!!!
// the elements of arr2 can be down casted as in (1) or (2)
// (3) is just an equivalent of
typealias U = P1
let arr3: Array<U> = arr.map { (element) -> U in
element as U
}
print(arr3.dynamicType) // Array<P1>
// the array must be converted, all the elements are down casted in arr3 from A to P1
// the compiler knows the type so ii do the job like in lines (1) or (2)