【问题标题】:NSString is not implicitly convertible to String - but everything is NSStringNSString 不能隐式转换为 String - 但一切都是 NSString
【发布时间】:2016-03-11 07:43:59
【问题描述】:

我正在编写为NSMutableURLRequest 设置Authorization: 标头的代码:

private func setAuthHeader(request: NSMutableURLRequest) {

    let plain       = NSString(format: "%@:%@", self.userName, self.password)
    let plainBytes  = plain.dataUsingEncoding(NSUTF8StringEncoding)!
    let headerValue = NSString(format: "Basic %@", plainBytes.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0)))

    request.setValue( headerValue, forHTTPHeaderField: "Authorization" )
}

但是当我为setValue 选择“转到定义”时,Xcode 显示为:

- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field;

所以setValue 需要一个NSString 参数值,而headerValue 是我的NSString 类型的参数。

然而 Swift 编译器给了我这个错误信息:

RestClient.swift:33:21: 'NSString' 不能隐式转换为 'String';您的意思是使用 'as' 来显式转换吗?

String 是从哪里得到的?

自动修复是把它改成这样:

request.setValue( headerValue as String, forHTTPHeaderField: "Authorization" )

...但为什么认为这是必要的?

【问题讨论】:

    标签: string swift nsstring


    【解决方案1】:

    实际上,您在问题中给出的定义是 setValue 函数的 Obj-C 签名。 Swift 函数具有以下声明,您可以在 Apple 的 NSMutableURLRequest here 文档中看到:

    声明

    func setValue(_ value: String?, forHTTPHeaderField field: String)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 2011-12-21
      • 2011-04-02
      • 2011-03-17
      相关资源
      最近更新 更多