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: Stringvar age: Int
or by entering data in it
var name ="Sedat"var age =44
But 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 patternvar age // Error: Type annotation missing in pattern
Sometimes 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 typevar age =nil// Error: 'nil' requires a contextual type
And 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
var name: String?=nilvar age: Int?=nil
Unwrapping the Variable
Nil-Coalescing
// if the result is "nil", prints "Anonymous"structBook {let title: Stringlet author: String?}let book =Book(title:"Beowulf", author:nil)let author = book.author ??"Anonymous"print(author)sw// print: Anonymous
// if the result is "nil", prints "0"let input =""let number =Int(input)??0print(number)// print: 0