Types and type casting - RaduG/swift_learning GitHub Wiki

Checking if an object is of a certain type

Use the is operator:

let a = 100
a is Int // true

Downcasting

Use as? to return an Optional or as! to force-unwrap.

class Item {
  let name: String

  init(titled name: String) {
    self.name = name
  }
}

class Movie: Item {}
class Song: Item {}
class Photo: Item {}

let items = [
  Movie(titled: "Inception"),
  Song(titled: "Bohemian Rhapsody"),
  Photo(titled: "Polar Bear")
] // this is inferred to be an [Item]

for item in items {
  if item is Movie {
    print("Movie: \(item.name)")
  } else if item is Song {
    print("Song: \(item.name)")
  } else if item is Photo {
    print("Photo: \(item.name)")
  }
}

// or
for item in items {
  if let movie = item as? Movie {
    print("Movie: \(movie.name)")
  } else if let song = item as? Song {
    print("Song: \(song.name)")
  } else if let photo = item as? Photo {
    print("Photo: \(photo.name)")
  }
}

Nonspecific types

  • Any - matches any object instance, including functions
  • AnyObject - matches only class instances