4

I am trying to convert a device token and using the following code (swift 3):

parameters["device_token"] = request.deviceToken.reduce("", {$0 + String(format: "%02X", $1)}). 

However I am getting the compiler error Binary operator '+' cannot be applied to operands of type Any? and String. What am I doing wrong here?

KexAri
  • 3,767
  • 5
  • 38
  • 74

2 Answers2

6

try this

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)
 }
Anbu.Karthik
  • 80,161
  • 21
  • 166
  • 138
0

Actually your code using reduce to convert the device token to a hex string is correct. But apparently parameters has the type NSMutableDictionary (or [String: Any]), and the compiler tries to match the initial value "" to Any?.

As a workaround, you can assign the hex string to a temporary variable first:

let hexToken = request.deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
parameters["device_token"] = hexToken

or use the trailing closure syntax instead:

parameters["device_token"] = deviceToken.reduce("") {$0 + String(format: "%02X", $1)}

Both methods make your code compile, so this could be a compiler bug.

Martin R
  • 510,973
  • 84
  • 1,183
  • 1,314