Type inference
Defining variables types
Type inference
Defining variables types
0
0
Checkbox to mark video as read
Mark as read

In all our articles we always defined each variable type. This was intended to not cofuse the reader since this is not always necessary.

As we said in the first variable article, Xcode needs to know the type of each variable we are creating, but the truth is that Xcode can infere the type most of the times.

Let's see some exemples where Xcode will infere our variable types:

let name = "Pablo" // String
let age = 2 // Int
let money = 23.89 // Double
let namesArray = [
    "Pablo",
    "Andrea",
    "Clara",
    "Mateo"
]

In these cases the type is clear because it's actually indirectly specified at the right side of the =. However, there are some cases this cannot be infered, we can see this clearly if we declare two enum with similar cases.

enum ShippingStatus {
    case preparing
    case sent
}

enum OrderStatus {
    case preparing
    case ready
}

let status = .preparing // ⚠️ ERROR

In this case, there is no hint of what enum we want to use, so we need to specifiy the type. There are multiple possibilities:

let statusA = OrderStatus.preparing // ✅
let statusB: OrderStatus = .preparing // ✅

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy