- Swift 4 Programming Cookbook
- Keith Moon
- 186字
- 2025-04-04 18:15:56
There's more...
While we defined constants and variables earlier, we also defined the type of thing we are assigning to explicitly. For example, consider the following:
let clearlyAString: String = "This is a string literal"
Swift is a statically typed language, which means any constant or variable that we define has to have a specific type, which cannot be changed. However, in the preceding line, the clearlyAString constant is clearly a String! The right-hand side of the expression is a String literal, and therefore we know that the left-hand side will be a String. More importantly, the compiler also knows this. Swift is all about being concise, so since the type can be inferred by the compiler, we do not need to explicitly state it. Try the following instead, and see whether you can run the code:
let clearlyAString = "This is a string literal"
In fact, all the type declaration that we have made so far can be removed! So, go back through the code we have already written and remove all type declarations (:String, :Int, :Float, and :Bool), as they can all be inferred.