Optionals
Overview
When you assign data to a variable, that data defines the data type. But "nil" does not have a data type. Therefore Swift will throw an error.
Every time you create a variable, you must define its type, whether by explicitly defining it
var name: String
var age: Intor by entering data in it
var name = "Sedat"
var age = 44But if you neither not define the type nor do not enter data into a variable, swift cannot know the type of the variable.
var name // Error: Type annotation missing in pattern
var age // Error: Type annotation missing in patternSometimes you may not want to define its type in advance. In such a situation, it will be empty. So entering "nil" does not solve the problem because it does not have any data type.
var name = nil // Error: 'nil' requires a contextual type
var age = nil // Error: 'nil' requires a contextual typeAnd sometimes you can define the data type but you don't exactly know which type is it, in such a situation you may think adding a "nil" may solve it, but it does not
var name: String = nil // Error: 'nil' cannot initialize specified type 'String'
var age: Int = nil // Error: 'nil' cannot initialize specified type 'String'But adding an optional sign "?" to the type may solve the problem
Unwrapping the Variable
Nil-Coalescing
Optional Binding
Optional Chaining
Source: HWS
Sources
Videos
Articles / Documents
Last updated
Was this helpful?