ios - Cannot Initialise Variable for type Unsafepointer Swift 3.0 conversion -
hi converting existing swift 2.0 code swift 3.0 came across error while conversion:
cannot invoke initializer type 'unsafepointer' argument list of type '(unsaferawpointer)'
here code:
extension data { var hexstring : string { let buf = unsafepointer<uint8>(bytes) // here error let chara = uint8(unicodescalar("a").value) let char0 = uint8(unicodescalar("0").value) func itoh(_ i: uint8) -> uint8 { return (i > 9) ? (chara + - 10) : (char0 + i) } let p = unsafemutablepointer<uint8>.allocate(capacity: count * 2) in 0..<count { p[i*2] = itoh((buf[i] >> 4) & 0xf) p[i*2+1] = itoh(buf[i] & 0xf) } return nsstring(bytesnocopy: p, length: count*2, encoding: string.encoding.utf8.rawvalue, freewhendone: true)! string } }
in swift 3 have use withunsafebytes()
access raw bytes of data
value. in case:
withunsafebytes { (buf: unsafepointer<uint8>) in in 0..<count { p[i*2] = itoh((buf[i] >> 4) & 0xf) p[i*2+1] = itoh(buf[i] & 0xf) } }
alternatively, use fact data
collection of bytes:
for (i, byte) in self.enumerated() { p[i*2] = itoh((byte >> 4) & 0xf) p[i*2+1] = itoh(byte & 0xf) }
note there problem in code:
nsstring(..., freewhendone: true)
uses free()
release memory, means must allocated malloc()
.
other (shorter, potentially less efficient) methods create hex representation of data
value can found @ how convert data hex string in swift.
Comments
Post a Comment