Brian Brian - 1 month ago 17
Swift Question

ascii to string swift 3 problems

In former versions of swift the following code worked.

let letterString = String( UnicodeScalar( 97 ) )
print( letterString )


returns "a"

After upgrading to swift 3 it suggested I change to

let letterString = String( describing: UnicodeScalar( 97 ) )
print( letterString )


returns Optional("a")

Okay so i tried adding the ! operator to unwrap but it doesn't work.

let letterString = String( describing: UnicodeScalar( 97 ) )
print( letterString! )


gives error: Cannot force unwrap value of non-optional type 'String'

Can anyone tell me what is going on here? How can I get an unwrapped String value from an ascii value in Swift 3?

Answer

It's not the String instance that's optional. It's the UnicodeScalar struct. So you have to unwrap that one:

let letterString = String(describing: UnicodeScalar(97)!)
print(letterString)

An alternative is to use UnicodeScalars other initializer. Then you don't need to unwrap it at all.

let letterString2 = String(describing: UnicodeScalar(UInt8(97)))
print(letterString)
Comments