generics - 带有数组的 Swift countElements()

标签 generics casting swift

问题

是否可以在我的设置中使用 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/

相关文章:

generics - Dart:有限制地扩展了通用类

Java模板函数

java - 通用 : extends Number & Comparable Basic understanding

python - 正确的方法是使用类型提示/泛型来描述类型类 ("type"的参数)

c++ - 是否可以指定按位操作的返回类型?

PostgreSQL bool 值转换(0 为假)

c# - 如何转换 CreateInstance 的返回值

ios - CIImage contentsOfUrl 无法将 UIImage 转换为 PNG

ios - Collection View 单元格未出现在 Collection View 中?

ios - 如何在 UITextView 中为文本添加轮廓?