问题
我能否在我的设置中使用 countElements()
函数来计算一个 Array
的元素数量?
问题详述
countElements()
可以正常处理 String
。但是我无法强制将 thing
转换为 Array
,从而无法调用 countElements()
。
请注意,方法签名必须为 func myCount(thing: Any?) -> Int
,因为这将会被用于我的开源项目。
func myCount(thing: Any?) -> Int {
if thing == nil {
return -1
}
if let x = thing as? String {
return countElements(x)
}
if let y = thing as? Array<Any> {
return countElements(y) // this if is never taken
}
return -1
}
myCount(nil) // -1
myCount("hello") // 5
myCount([1, 2, 3]) // BOOM, returns -1, I'm expecting 3 returned
y.count
而不是将其转换回Array
。 - vacawamaNSArray
和Array
之间进行类型转换使其工作?谢谢。 - Unheilig