Swift向下转换对象数组

时间:2016-05-16 20:40:48

标签: swift

import Foundation

class A: NSObject {

}

class B: A {

}

let array = [B(),B(),B(),B()]

array as? [A] //this does not works

B() as? A // this works

2 个答案:

答案 0 :(得分:1)

as?是一个条件向下转换操作(可能会失败,因此会返回一个可选项) - 并且您正在尝试向上转换(其中永远不会失败,因此你可以自由地做。)

因此,您可以使用as来自由地向上转换数组 - 或依赖类型推断,正如Casey所说。

let arrayOfB = [B(),B(),B(),B()]

let arrayOfA = arrayOfB as [A] // cast of [B] to [A] via 'as'

let explicitArrayOfA : [A] = arrayOfB // cast of [B] to [A] via inference of explicit type 

func somethingThatExpectsA(a:[A]) {...}

somethingThatExpectsA(arrayOfB) // implicit conversion of [B] to [A]

虽然编译器的A is not a subtype of B错误在上下文中无疑是无益的。更合适的错误(或者可能只是警告)可能是'as?' will always succeed in casting '[B]' to '[A]' – did you mean to use 'as'?

你还应该注意到你的例子:

B() as? A // this works

您将收到编译器警告Conditional cast from 'B' to 'A' always succeeds。虽然为什么你得到编译器警告,而不是错误 - 我不能说。我怀疑它是由于special way in which array casting happens

答案 1 :(得分:1)

因为B是A,你可以放弃条件转换和

let thing = array as [A]

或者将目的地声明为所需类型并忘记投射

let thing : [A] = array