使用Swift 2.1
我正在寻找一种将非可选类型数组分配给可选类型数组的好方法,其中类型相同。以下是我尝试过的一些内容:
var foos: [Int?] = []
let bars: [Int] = []
foos = bars // Error: Cannot assign value of type '[Int]' to type '[Int?]'
foos = bars as [Int?] // Error: Cannot convert value of type '[Int]' to type '[Int?]' in coercion
foos = bars as? [Int?] // Error: 'Int?' is not a subtype of 'Int'
foos = bars.map { $0 } // Works but I think there must be a better way
为可选类型指定非可选类型在Swift中可以正常工作。我不明白为什么这对阵列也不起作用。
var foo: Int? = nil
let bar: Int = 0
foo = bar // Works fine
有什么想法吗?
答案 0 :(得分:0)
您可以使用:
var array3:[Int] = []
var array4:[AnyObject] = []
array4 = array3
答案 1 :(得分:0)
您可以使用几个看似类型转换的通用函数使语法更加可口:
var foos: [Int?] = []
let bars: [Int] = []
let fums: [Int64?] = []
func CastArray<T, U>(array:[T?]) -> [U?]
{ return array.map({ $0 as! U? }) }
func CastArray<T, U>(array:[T]) -> [U?]
{ return array.map({ $0 as? U }) }
foos = CastArray(bars)
foos = CastArray(fums)