xcode Swift-3 错误:'-[_SwiftValue unsignedIntegerValue]:无法识别的选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39643394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift-3 error: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector
提问by Tapas Pal
Following code was perfectly worked with old swift. This is an extension of String
以下代码与旧的 swift 完美配合。这是 String 的扩展
func stringByConvertingHTML() -> String {
let newString = replacingOccurrences(of: "\n", with: "<br>")
if let encodedData = newString.data(using: String.Encoding.utf8) {
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) //Crash here
return attributedString.string
} catch {
return self
}
}
return self
}
But in swift 3 it crashes saying
但是在 swift 3 中它崩溃了说
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x6080002565f0'
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[_SwiftValue unsignedIntegerValue]:无法识别的选择器发送到实例 0x6080002565f0”
Anyone please suggest me what need to do?
任何人请建议我需要做什么?
回答by Sachin Vas
I ran into the same problem:
我遇到了同样的问题:
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
]
Here the String.Encoding.utf8
the type check fails. Use NSNumber(value: String.Encoding.utf8.rawValue)
这里String.Encoding.utf8
类型检查失败。用NSNumber(value: String.Encoding.utf8.rawValue)
回答by zidanex
In Swift3 no cast to AnyObject is needed anymore and also no NSNumber.
在 Swift3 中,不再需要转换为 AnyObject,也不需要 NSNumber。
let attrs: [String: Any] = [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
回答by Peter Kuennemann
This post saved my day. After migrating to Swift 3, the little change String.Encoding.utf8
to String.Encoding.utf8.rawValue
fixed the trap reported here.
这篇文章拯救了我的一天。迁移到 Swift 3 后,修复陷阱的小改动 String.Encoding.utf8
在String.Encoding.utf8.rawValue
这里报告。
Orignal line:
原线:
...
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8],
...
changed to
变成
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
add the .rawValue
to the end...
添加.rawValue
到最后...