Swift: How to convert a String to UInt8 array?

后端 未结 4 608
死守一世寂寞
死守一世寂寞 2020-12-28 12:14

How do you convert a String to UInt8 array?

var str = \"test\"
var ar : [UInt8]
ar = str
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 12:39

    I came to this question looking for how to convert to a Int8 array. This is how I'm doing it, but surely there's a less loopy way:

    Method on an Extension for String

    public func int8Array() -> [Int8] {
        var retVal : [Int8] = []
        for thing in self.utf16 {
            retVal.append(Int8(thing))
        }
        return retVal
    }
    

    Note: storing a UTF-16 encoded character (2 bytes) in an Int8 (1 byte) will lead to information loss.

提交回复
热议问题