Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 Swift 5.5, iOS 15, Xcode 13

Part 3: Coding in Swift

28. Type Inference

Lesson Complete

Play Next Lesson
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 27. Variables & Constants Next episode: 29. Conclusion

This video was last updated on Jan 11 2022

We’ve now reduced our points(sliderValue:) to just a few lines of code.

But good news - there’s a way to reduce the code by a few more characters, thanks to an amazingly handy feature of Swift called type inference. Let’s take a look.

Look at points(sliderValue:), and explain type inference

Remove types as follows:

func points(sliderValue: Int) -> Int {
  let difference = abs( - sliderValue)
  let awardedPoints = 100 - difference
  return awardedPoints

Remove for properties as well:

var target = Int.random(in: 1...100)
var score = 0
var round = 1

Show how you can option-click to verify that it is correct.

Go to ContentView.swift and update also:

@State private var alertIsVisible = false
@State private var sliderValue = 50.0
@State private var game = Game()

Remove for roundedValue:

let roundedValue = Int(self.sliderValue.rounded())

Explain how you can get rid of self. in many cases too, and remove it throughout the app.

Go back to Game.swift’s points(sliderValue:) method. Say there’s a way we can simplify this from 3 lines of code down to one.

Replace the line with:

return 100 - abs( - sliderValue)

Then explain how there’s antoher handy thing type inference can do for you. If you have a method that returns a value and only has one line of code, you don’t need to put return. The compiler can infer that since there’s only one line of code, the result of that line will be what is returned from the method. So update the method to this:

100 - abs( - sliderValue)