2016-09-22 216 views
43

以下代码与旧swift完美结合。这是字符串Swift-3错误:' - [_ SwiftValue unsignedIntegerValue]:无法识别的选择器

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 
} 

的扩展,但在迅疾3崩溃说

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x6080002565f0'

请人建议我有什么需要做什么?

回答

81

我遇到了同样的问题:

let attributedOptions : [String: AnyObject] = [ 
      NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject, 
      NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject 
     ] 

这里String.Encoding.utf8类型检查失败。使用NSNumber(value: String.Encoding.utf8.rawValue)

+12

由于它的正常工作。但它会是'NSNumber(value:String.Encoding.utf8.rawValue)' –

+0

Lifesaver! (PS:还需要NSNumber(..)才能工作,你可以更新答案来包含它吗?) – Marchy

+6

你应该只需要'String.Encoding.utf8.rawValue',因为Swift会自动转换'Int's当一个Swift字典传递给一个需要'NSDictionary'的函数时,将'UInt's转换成'NSNumber's。尽管这需要将swift字典作为一个'[String:Any]'数组。另请参见[this](https://developer.apple.com/swift/blog/?id=39)Swift博客条目。 – MaddTheSane

42

在Swift3中,不再需要转换为AnyObject,也不需要NSNumber。

let attrs: [String: Any] = [ 
      NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, 
      NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue 
     ] 
+1

的任何解决方案我会说这是清理方法。 –

3

此帖保存了我的一天。迁移到Swift 3后,稍微更改String.Encoding.utf8String.Encoding.utf8.rawValue修复了此处报告的陷阱。

一部开拓创新的路线:

... 
    options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, 
       NSCharacterEncodingDocumentAttribute: String.Encoding.utf8], 
... 

改为

options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, 
      NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], 
相关问题