I have done C, C++, Java and these language taught me that characters are enclosed with in single quotes(mostly when abiding to proper syntax) but strings are double quoted. Is it swift's syntax that only allows characters to be inside of single quotes or there is some valid reason(logic) behind offering this kind of syntax.
let char1: Character = "A" //correct
let char2: Character = 'B' //incorrect
To include quotes inside a string in Swift, escape the quote symbol with backslash character, i.e., place a backslash character before the double quote inside the string.
Swift CharacterCharacter is a data type that represents a single-character string ( "a" , "@" , "5" , etc). Here, the letter variable can only store single-character data.
The The Swift Programming Language / Strings and Characters states: You can place a string literal within extended delimiters to include special characters in a string without invoking their effect. You place your string within quotation marks ( " ) and surround that with number signs ( # ).
The state of the compiler technology has changed a great deal since the time the first C compiler was developed. Compilers became a lot smarter about figuring out things on their own, including the intended type of expressions, without help from programmers.
Figuring out char
vs. string literals is one such example. Theoretically, the structure of today's C allows to infer the type of a literal in many contexts. For example, in the code below the compiler has enough information to treat single-character strings as if they were character literals:
void foo(char c);
char s[] = "xyz";
// None of the below would compile
char a = "a";
foo("b");
if (s[1] == "c") {
...
}
Back at the time, however, it was easier to ask the programmer to tell the compiler that "a"
, "b"
and "c"
are actually 'a'
, 'b'
, and 'c'
. Moreover, since function prototypes were not introduced until ANSI C, foo("b")
inference was not even possible in the original K&R version of the language.
Programmer's help is no longer required when the language has type inference system, so Swift designers decided to unify the syntax for string and character constants.
There's no such thing as a single quote in Swift.
The only way to declare a character is to use the explicit Character
type.
let a: Character = "a"
You can read more about Swift's lexical structure here https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With