Understanding UnicodeScalar initializers in Swift

2019-05-11 07:40发布

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?

1条回答
SAY GOODBYE
2楼-- · 2019-05-11 08:33

"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)
查看更多
登录 后发表回答