Sometimes, it feels like programmers want to sound sophisticated and instead of saying “text” and “number”, they say “string” and “integer”, but it’s more complicated.
These are two of the most common types of values you can store to constants or variables as you already know. But once you initialy store a specific type of value to a variable, you can’t change that data type later.
You can change the value, but the new value must be of the same type. For example, you can change one String value to another one, but you can’t change String to Integer.
Let’s test this in our playground.
When I try to change my age to “42”, Xcode will protest, because I try to store String (quotes are used for text so even though 42 is a number, it’s treated as a text) to the variable that holds only Integers. It’s like trying to fit rectangle into a circle.
In case you wonder, Strings consist of characters strung together, like beads in a necklace, hence the name.
Ok, delete the last line of code and remember that you must respect the type you used when you created your variable.
In Swift, you can place any type of variable right inside your string, you just need to write a backslash, \, followed by a variable name in parentheses. This feature is called string interpolation.
varscore=50varstr="Your score is \(score)"
The output of the str variable will be “Your score is 50”.