我正在尝试转换设备令牌,并使用以下代码(swift 3):
parameters["device_token"] = request.deviceToken.reduce("", {$0 + String(format: "%02X", $1)}). 然而,我得到编译器错误Binary operator '+' cannot be applied to operands of type Any? and String。我在这里做错什么了?
发布于 2016-10-04 04:00:32
尝尝这个
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
}发布于 2016-10-04 05:23:45
实际上,使用reduce将设备令牌转换为十六进制字符串的代码是正确的。但显然,parameters具有NSMutableDictionary (或[String: Any])类型,编译器试图将初始值""与Any?匹配。
作为解决办法,您可以首先将十六进制字符串赋值给一个临时变量:
let hexToken = request.deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
parameters["device_token"] = hexToken或者使用尾随闭包语法代替:
parameters["device_token"] = deviceToken.reduce("") {$0 + String(format: "%02X", $1)}这两种方法都会使您的代码编译,因此这可能是一个编译器错误。
https://stackoverflow.com/questions/39843937
复制相似问题