0

I am getting an error while converting my code to Swift 3.0. My sample code is below:

func hexRepresentation()->String {

    let dataLength:Int = self.count
    let string = NSMutableString(capacity: dataLength*2)
    let dataBytes:UnsafeRawPointer = (self as NSData).bytes

    for idx in 0..<dataLength {
         string.appendFormat("%02x", [UInt(dataBytes[idx])] as String )
    }

    return string as String
}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
S Ilyas
  • 21
  • 3
  • 3
    Compare [How to convert Data to hex string in swift](https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift) for simpler methods to create hex encoded string representation of a Data value. – Martin R Sep 18 '17 at 08:19
  • 1
    Also, for those times when you actually do need to access a `Data` object's byte pointer (which isn't this case, but still), it's much preferable to use `.withUnsafeBytes()` rather than casting to `NSData` and using its `.bytes`, to avoid the superhappyfuntimes that can result if the `Data`'s storage gets reaped sooner than you think it will. – Charles Srstka Sep 18 '17 at 08:33
  • ... which is what I suggested in response to his/her previous question https://stackoverflow.com/q/46169483/1187415 :) – Martin R Sep 18 '17 at 08:34

1 Answers1

0

What does this line do:

 string.appendFormat("%02x", [UInt(dataBytes[idx])] as String )

First of all, it takes the byte at index idx in dataBytes and wraps it in an array. This is the array literal referred to in the error message.

Next it tries to cast the array as a String - not convert: cast. This the compiler knows to be impossible, hence the error message.

Fortunately, you don't want to convert the argument to a string because your format specifier asks for a UInt (%x), so what you really want here is just

string.appendFormat("%02x", UInt(dataBytes[idx]))

As for getting the bytes, the Swift type Data has a function foreach which is handy for iterating the bytes:

self.forEach { string.appendFormat("%02x", UInt($0)) }
JeremyP
  • 84,577
  • 15
  • 123
  • 161