请考虑以下示例:
let a: Int! = 1
let b: Int! = 2
let array = [a, b]
print(type(of: array)) // prints: Array<Optional<Int>>
为什么推断类型为数组[Int?]
而不是[Int]
或[Int!]
?我认为隐式展开处理可选的for good,存在运行时错误的风险。但是为了获得数组的非可选[Int]
类型,我需要手动执行以下操作之一:
let array1 = [a!, b!]
let array2: [Int] = [a, b]
let array3 = [a, b] as [Int]