Suragch
Suragch

Reputation: 512776

Characters and Strings in Swift

Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways:

let narrowNonBreakingSpace: Character = "\u{202f}"
let narrowNonBreakingSpace = "\u{202f}"

As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes (and not single quotes for characters). I've seen several examples, though, where the second form (without Character) is used even though the variable is only holding a single character. Is that people just being lazy or forgetting to write Character? Or does Swift take care of all the details and I don't need to bother with it? If I know I have a constant that contains only a single Unicode value, should I always use Character?

Upvotes: 4

Views: 1210

Answers (2)

Nate Cook
Nate Cook

Reputation: 93296

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise you'll just need to convert to String every time you need to use it.

Upvotes: 5

donnywals
donnywals

Reputation: 7601

The Swift compiler will infer the type of the string to actually be character in the second case. Adding : Character is therefor not really needed. In this case I would add it though because it's easy to mistakenly assume that this Character is a String and another developer might try to treat it as such. However, the compiler would throw errors because of that since it inferred the type of this String to not be a String but a Character.

So in my opinion adding Character is not a matter of being lazy or forgetting it, it's a matter of trusting the compiler to correctly infer the type of this constant en to rely on the compiler throwing the correct error whenever I try to use this constant wrong.

Swift's compiler basically takes care of all the details and it doesn't really matter if you add Character, the compiler will (should) take care of it.

Upvotes: -2

Related Questions