Victor Sigler
Victor Sigler

Reputation: 23449

Understanding UnicodeScalar initializers in Swift

If we then look at the struct UnicodeScalar, we see this initializer:

init(_ v: UInt32)

But you can do this without any problem :

println(UnicodeScalar("a").value)

An it prints out:

97

But if you try it to do this :

let a : Character = "a"  // With String gave error too        
println(UnicodeScalar(a).value)

Its give you an error regarding the initializer of the UnicodeScalar struct.

I assume that in the first case it make a implicit cast or something in the initializer , but why not in the second case?

How can avoid the error in the seconde case using a declared variable?

Upvotes: 3

Views: 235

Answers (1)

matt
matt

Reputation: 535306

"a" is not like a. a is a variable, so its type is Character or String. "a" is a literal, and its type is StringLiteralConvertible. That is why "a" can be used in places that a cannot be used.

(The same is true for literals in general in Swift. You can use the literal 9 in places where you cannot use an Int variable whose value is 9.)

Perhaps you are looking for something like this:

let c  = "a"
let v = c.unicodeScalars
let u = v[v.startIndex]
println(u.value)

Upvotes: 4

Related Questions