【问题标题】:Swift countElements() with an array带有数组的 Swift countElements()
【发布时间】:2014-09-17 22:17:49
【问题描述】:

问题

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

【问题讨论】:

    标签: generics casting swift


    【解决方案1】:

    这对我有用。虽然来回投射,但感觉有点hacky。

    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
    }
    

    【讨论】:

    • 您也可以return y.count 而不是将其转换回Array
    • 这很好。我只是专注于让 countElements 工作
    • 我会让它返回一个可选项,这样就不会在最后返回 -1,而是 nil。
    • 您能解释一下为什么通过在NSArrayArray 之间来回转换它可以工作吗?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多