【问题标题】:Swift 1.2 not willing my NSString "+" map.reduceSwift 1.2 不愿意我的 NSString "+" map.reduce
【发布时间】:2015-04-11 10:38:08
【问题描述】:

这是在 Swift 1.1 中完美运行的代码

在我的课开始时,我有

var bytes = [UInt8]?()

后来我有

func hexString() -> String? {
    if let b = bytes {
        return b.map({NSString(format: "%02x", $0)}).reduce("", +)
    }
    return nil
}

Swift 1.2 给了我

调用中缺少参数标签“combine:”

因此希望我以这种方式改写我的地图减少

return b.map({NSString(format: "%02x", $0)}).reduce("", combine: +)

注意第二个reduce 参数的显式combine。如果我这样做,尽管我在+ 上遇到另一个错误:

找不到接受所提供参数的“+”重载

这个错误对我来说毫无意义,因为 NSString(format:) 产生的是一个 NSString,所以它应该与 + 一起使用,对吧?

【问题讨论】:

    标签: cocoa swift mapreduce nsstring operator-overloading


    【解决方案1】:

    我认为问题在于 NSString 没有实现“+”运算符,只有 String 可以。在 Swift 1.1 中,NSString 被自动转换为 String。

    这就是为什么你应该使用 String 而不是 NSString。

    func hexString() -> String? {
        if let b = bytes { 
            return b.map({String(format: "%02x", $0)}).reduce("", combine: +)
        }
        return nil
    }
    

    【讨论】:

    • 谢谢@ps4。请参阅我对 valzevul 的评论——您在 2 分钟后回复了完全相同的答案!太棒了:-)
    【解决方案2】:

    似乎这是因为 Swift 1.2 禁用了桥接。这种替换不会产生错误:

    var bytes = [UInt8]?()
    
    func hexString() -> String? {
        if let b = bytes {
            return b.map() {String(format: "%02x", $0)}.reduce("", combine: +)
        }
        return nil
    }
    

    【讨论】:

    • 感谢@valzevul 是的,这是我转换过程中最疯狂的原因;)不过这是件好事,因为这样我们必须使用比 NSString 更多的 String!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多