[Swift] Int vs Optional Int

Int

  • 10
  • Int
  • Store Int-type values

Optional Int

  • Optional(10)
  • Int?
  • Int!
  • Store Int-type values or nil(no value)
print(Int("100"))
// Optional(100)

print(Int("100")!)
// 100
print(Int("Hi"))
// nil

print(Int("Hi")!)
// error

Primary Type cannot store nil in Siwft. Optional type store nil

The optional type provides a safe way to handle situations where no value is assigned to a variable or constant

forced unwrapping 1

var x : Int?
var y : Int = 0
x = 10
print(x)  // Optional(10)
print(x!) // 10, forced unwrapping
print(y)  // 0
var x : Int?
print(x) // nil
var x : Int?
x = 10
if x != nil {
	print(x!)
} else {
	print("nil")
}

var x1 : Int?
if x1 != nil {
	print(x1!)
} else {
	print("nil")	   
}

if x != nil (NOT if x!=nil)

forced unwrapping 2 : optional binding

if let constName = optionalName {
    //if optionalName has value, unwrapping and store the value to constName. if optionalName is nil, conditional statement is not execute
}

if var varName = optionalName {
    //if optionalName has value, unwrapping and store the value to varName. if optionalName is nil, conditional statement is not execute
}
var x : Int?
x = 10
if let i = x {
	print(i)
} else {
	print("nil")
}
var x1 : Int?
if let j = x1 {
	print(j)
} else {
	print("nil")	   
}

Multiple optional Unwrapping

var person1: String?
var person2: String?

person1 = "male"
person2 = "female"

if let firstPerson = person1, let secondPerson = person2 {
	print(firstPerson, secondPerson)
} else {
	print("nil")
}

Two optional types : Int? vs Int!

var x : Int?
var y : Int!

var y : Int! type of optional used a lot to initialize outlet variables in a class

Use if the option always has a valid value

let x : Int? = 1
let y : Int = x!
let z = x
print(x, y, z) 
// Optional(1) 1 Optional(1)
print(type(of:x), type(of:y), type(of:z))
//Optional<Int>, Int, Optional<Int>

let a : Int! = 1
let b : Int = a // Unwrap automatically if not used as Optional
let c : Int = a!
let d = a //Can be used as optional, so it is optional
let e = a + 1
print(a, b, c, d, e)
// Optional(1) 1 1 Option(1) 2
print(type(of:a), type(of:b), type(of:c), type(of:d), type(of:e))
// Optional<Int> Int Int Optional<Int> Int

Why use optional?

  • Only optional can have nil.
    var i = nil // error
    var i : Int? = nil // Ok
    var i : Int? // Ok
    // optional variable automatically initializes to nil if not initialized
    var str : String = nil // Invalid code
    let str = nil // Invalid code
    
  • If a constant or variable has no value, it need to be declared as an optional type.