简体   繁体   中英

How to convert Int8 to Character?

I need to convert Int8 to Character . How can I do it?

I tried use UnicodeScalar

var result += Character(UnicodeScalar(data[i]))

... but got this error:

Cannot invoke initializer for type 'UnicodeScalar' with an argument list of type (Int8)

也许您只需要将整个数据转换为字符串即可:

var result = String(data: data, encoding: .ascii)

Unicode.Scalar can be initalized just with paramaters of certain types which you can find in docs .

I would suggest you using init(_:) which takes UInt8 which tells that given number is positive (this is required for creating UnicodeScalar ). So, you can try to cast your Int8 to UInt8 and then your initializer takes parameter of correct type

let int: Int8 = data[i]
if let uint = UInt8(exactly: int) {
    let char = Character(UnicodeScalar(uint))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM