Understanding type inference and type safety
In the previous section, you declared constants and variables and assigned values to them. Swift automatically determines the constant or variable type based on the value provided. This is called type inference. You can see the type of a constant or variable by holding down the Option key and clicking its name. To see this in action, follow these steps:
- Add the following code to your playground to declare a string:
let cuisine = "American"
- Click the Run button to run it.
- Hold down the Option key and click
cuisine
to reveal the constant type. You should see the following:
As you can see, cuisine
’s type is String
.What if you want to set a specific type for a variable or constant? You'll see how to do that in the next section.
Using type annotation to specify a type
You've seen that Xcode tries to automatically determine the data type of a variable or constant based on...