

Some people prefer to use type annotation, then assign an empty array to it like this: var cities: = Remember, you need to add the open and close parentheses when making empty arrays, dictionaries, and sets, because it’s where Swift allows us to customize the way they are created. However, if you wanted to create an empty array of strings, you’d need to know the type: var teams: = ()Īgain, the type annotation isn’t required, but you still need to know that an array of strings is written as so that you can make the thing. Type annotation isn’t needed there, because Swift can see you’re assigning an array of strings. For example, this creates an array of strings: var soda: = Knowing all these types is important for times when you don’t want to provide initial values. This must be specialized, such as : var user: = ) This must be specialized, such as : var albums: = ĭictionary holds lots of different values, where you get to decide how data should be accessed.

Int holds whole numbers: var luckyNumber: Int = 13ĭouble holds decimal numbers: let pi: Double = 3.141īool holds either true or false: var isAuthenticated: Bool = trueĪrray holds lots of different values, all in the order you add them. String holds text: let playerName: String = "Roy" We’ve looked at a few types of data so far, and it’s important you know their names so you can use the right type annotation when needed. Without the : Double part Swift would infer that to be an integer, but we’re overriding that and saying it’s definitely a decimal number. That’s exactly what Swift’s type inference would have done anyway, but sometimes it isn’t – sometimes you will want to choose a different type.įor example, maybe score is a decimal because the user can get half points, so you’d write this: var score: Double = 0 Now we’re being explicit: surname must be a string, and score must be an integer. Type annotations let us be explicit about what data types we want, and look like this: let surname: String = "Lasso" This uses type inference: Swift infers that surname is a string because we’re assigning text to it, and then infers that score is an integer because we’re assigning a whole number to it. So far we’ve been making constants and variables like this: let surname = "Lasso" However, sometimes we don’t want to assign a value immediately, or sometimes we want to override Swift’s choice of type, and that’s where type annotations come in. Swift is able to figure out what type of data a constant or variable holds based on what we assign to it.
