Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Type Inference in Swift
Written by Team Kodeco

In Swift, you can use type inference to automatically infer the data type of a variable or constant based on the value assigned to it. Type inference allows you to declare a variable or constant without explicitly specifying its data type.

For example, to declare a variable as a string, you can use the following syntax:

var message = "Hello, World!"

In this example, message is a variable whose data type is inferred by the compiler to be String based on the value “Hello, World!” assigned to it.

Similarly, you can use type inference to declare a constant as an integer:

let numberOfApples = 5

In this example, numberOfApples is a constant whose data type is inferred by the compiler to be Int based on the value 5 assigned to it.

In general, you should prefer to use type inference (rather than manual type annotation) wherever possible, as it makes your code more concise and readable.

© 2024 Kodeco Inc.