将项目升级到 Swift 4.2(从 4.0 转换)后,我遇到了
NSInvalidArgumentException
异常。
2018-09-19 15:37:33.253482+0100 <redacted>-beta[3715:1010421] -[Swift._EmptyArrayStorage _getValue:forType:]: unrecognized selector sent to instance 0x107e6c290
2018-09-19 15:37:33.254312+0100 <redacted>-beta[3715:1010421] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift._EmptyArrayStorage _getValue:forType:]: unrecognized selector sent to instance 0x107e6c290'
它与
NSMutableAttributedString
相关,代码正在添加一些属性,例如 NSAttributedString.Key.underlineStyle
。
当要分配属性字符串时会发生异常:
textView.attributedText = mutableAttributedString
。
代码在 Swift 4 中运行:
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.styleNone.rawValue, range: range)
但在 Swift 4.2 中,编译器建议将
NSUnderlineStyle.styleNone.rawValue
更改为 NSUnderlineStyle.none.rawValue
接受更改后,编译器开始抱怨“'none'不可用:使用[]构造一个空选项集”:
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.none.rawValue, range: range)
^~~~~ 'none' is unavailable: use [] to construct an empty option set
我刚刚发现代码出了什么问题。
因此,由于编译器错误“'none'不可用:使用[]构建空选项集”,我将
NSUnderlineStyle.none.rawValue
替换为[]
🤦u200d♂️,这是不对的这种情况是因为它使用的是 rawValue
,而不是 none
类型。
因此,修复方法是使用
0
。
错误:
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: [], range: range)
右:
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: 0, range: range)