Swift中使用countElements()函数计算数组的长度

3

问题

我能否在我的设置中使用 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
1个回答

2
这对我来说是有效的。虽然需要不断转换,但感觉有点投机取巧。
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
}

1
你也可以直接返回 y.count 而不是将其转换回 Array - vacawama
那是个好观点。我只是专注于让countElements工作。 - Connor
2
我会将其返回一个可选项,这样在结尾处不会返回-1,而是返回nil。 - erdekhayser
请问您为什么要通过在 NSArrayArray 之间进行类型转换使其工作?谢谢。 - Unheilig

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接