问题
是否可以在我的设置中使用 Array
调用 countElements()
?
问题详情
countElements()
与 String
配合使用效果很好。但是我不知道如何将 thing
转换为 Array
从而不调用 countElements()
。
请注意方法签名必须是func myCount(thing: Any?) -> Int
,因为这是used in my open source project .
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
最佳答案
这对我有用。虽然来回转换,但感觉有点老套。
func myCount(thing: Any?) -> Int {
if thing == nil {
return -1
}
if let x = thing as? String {
return countElements(x)
}
if let y = thing as? NSArray {
return countElements(y as Array)
}
return -1
}
关于generics - 带有数组的 Swift countElements(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25901226/