Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Type Checking in Swift
Written by Team Kodeco

Type checking is a way to verify the type of an object at runtime in Swift. This allows you to determine if an object is of a specific type and perform operations accordingly.

You can use the is operator to check if an object is of a specific type. If the type check succeeds, the result of the expression is true. For example:

class MediaItem {
  var name: String
  init(name: String) {
    self.name = name
  }
}

class Song: MediaItem {
  var artist: String
  init(name: String, artist: String) {
    self.artist = artist
    super.init(name: name)
  }
}

class Movie: MediaItem {
  var director: String
  init(name: String, director: String) {
    self.director = director
    super.init(name: name)
  }
}

let library = [Movie(name: "Avatar", director: "James Cameron"), Song(name: "Shake it Off", artist: "Taylor Swift")]

for item in library {
  if item is Song {
    print("This is a song")
  } else if item is Movie {
    print("This is a movie")
  }
}

In this example, the type of each item in the library array is checked using the is operator. Based on the type, the appropriate message is printed.

You can also use the as? operator to perform a type check and downcast the object to a specific type. If the type check fails, the expression returns nil. For example:

for item in library {
  if let song = item as? Song {
    print("Song: \(song.name), Artist: \(song.artist)")
  } else if let movie = item as? Movie {
    print("Movie: \(movie.name), Director: \(movie.director)")
  }
}

In this example, the type of each item in the library array is checked using the as? operator. If the type check succeeds, the object is downcast to the specific type and the appropriate message is printed.

Here’s an example of using guard statement to perform a type check and downcast an object to a specific type:

for item in library {
  guard let song = item as? Song else {
    continue
  }
  print("Song: \(song.name), Artist: \(song.artist)")
}

In this example, the guard statement is used to perform a type check using the as? operator. If the type check fails, the continue statement is executed and the next iteration of the loop begins. If the type check succeeds, the object is downcast to the specific type and the appropriate message is printed.

Using guard in this way can make the code more readable and eliminate the need for nested if statements.

© 2024 Kodeco Inc.