Cannot convert value of type "Character" to type "String" under coercion
In Swift, I expect the following to be completely correct code:
let snailCharacter: Character = "🐌"
let snailString = snailCharacter as String
But apparently it throws an error:
Cannot convert value of type "Character" to enter "String" in forced mode
The solution to this is to use an initializer String
like this:
let snailString = String(snailCharacter)
I thought I was Character
sort of a subset String
and it surprised me. Why is it forbidden to use Character
to String
?
I am using Swift 4 in Xcode 9 beta 4.
source to share
Looking at the documentation , you can see which Character
is one of several views String
in Swift
(highlighted by me in the relevant parts)
The string is a series of characters such as "hello world" or "Albatross". Swift strings are represented by string type. the contents of the string can be retrieved in a variety of ways, including how to collect character values.
B Swift
, String
is not just an array Character
, unlike some other languages. B Swift
, Character
is simply a way to represent an instance in a String
certain way. String
can be represented with View
s such as CharacterView
, utf8View
etc.
One of the key principles of type architecture Swift
String
was Unicode correctness, which is one of the reasons String
, not just an array of Character
s.
For more information on the changes String
to Swift4
see String Manifesto .
More specifically why casting doesn't work. There are two kinds of castings, injection molding and bridge casting. Type casting is only possible between classes in which inheritance is involved. You can either tailor a subclass to its superclass, which always succeeds, or you can try to demolish the superclass to a subclass that only works if the subclass instance was first forwarded to its superclass.
It should be pretty clear from the above explanation why type casting doesn't work between Character
and String
, since neither of the two types inherits from each other.
To bridge the casting is a method proposed by Apple for interaction between certain types Swift
and Foundation
like String
and NSString
, but because both String
, and Character
are Swift
the types of bridge casting has nothing to do with this problem.
source to share