What is "is" in Swift language? and how to use?

0 votes
110 views
asked Mar 30, 2015 in Swift by jonathan (3,105 points)
Hi All

What is "is" in Swift language? and how to use?

1 Answer

0 votes
answered Mar 30, 2015 by john (4,220 points)
Hi

  "is" is type checking operator in swift. It is used to check whether an instance is of a certain class type.

class MediaItem {

    var name: String

   init(name: String) {

      self.name = name

   }

}

 

class Movie: MediaItem {

   var director: String

   init(name: String, director: String) {

      self.director = director

      super.init(name: name)

  }

}

 

class Song: MediaItem {

   var artist: String

   init(name: String, artist: String) {

       self.artist = artist

       super.init(name: name)

   }

}

let library = [

    Movie(name: "Casablanca", director: "Michael Curtiz"),

    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),

    Movie(name: "Citizen Kane", director: "Orson Welles"),

    Song(name: "The One And Only", artist: "Chesney Hawkes"),

    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")

]

var movieCount = 0

var songCount = 0

for item in library {

    if item is Movie {

       ++movieCount

   } else if item is Song {

      ++songCount

  }

}
...