The Startup
Published in

The Startup

How Does Swift Type Inference Work?

Photo by Manuel Schulze

Swift — a statically typed language

function jsFunc() {
var value = 32;
value = “Hi, guys!”;
}
func swiftFunc() {
var value: Int = 32
value = "Hi, guys!"
}

Explicitly typed assignments

let stringLabel: String = "I am a string!"
var intValue: Int = 4

Implicitly typed assignments (Swift type inference)

let stringLabel = "I am a string!"
var intValue = 4

The limits of type inference

let floatValue = 70.0
let explicitFloatValue: Float = 70.0
let castedFloatValue = Float(70.0)
let floatValueWithAsFloat = 70.0 as Float
func testFunc() {
let myValue
let someCondition = true
if someCondition {
myValue = 2
} else {
myValue = 4
}
}
func testFunc() {
let myValue: Int
let someCondition = true
if someCondition {
myValue = 2
} else {
myValue = 4
}
}
let optionalValue = nil // Error
let workingOptional: String? = nil // Does work
let nonOptional = "Hello" // Constant of type String
var beCareful = nonOptional // Variable of type String (not String?)
var better: String? = nonOptional // Variable of type String?
beCareful = nil // Error, Swift thinks beCarful is of type String
better = nil // Does work, Swift knows its either String or nil

Bonus tip

let doubleValue = 70.0
let floatValue: Float = 30.0
let sum = doubleValue + floatValue // This fails

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Manuel Schulze

iOS developer from Germany who works as a contractor. Learning new things daily. Teaching Swift, iOS, macOS, watchOS, iPadOS, and tvOS programming.