斯威夫特的检查类型

时间:2014-12-09 10:41:23

标签: ios xcode swift

Here is swift tutorial link

示例是:

  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")
  ]

教程说: 如果迭代此数组的内容,则您收到的项目将被键入MediaItem,而不是Movie或Song。

检查类型说: 使用类型检查运算符(is)检查实例是否属于某个子类类型。如果实例属于该子类类型,则类型检查运算符返回true,否则返回false。

var movieCount = 0
var songCount = 0

for item in library {
  if item is Movie {
    ++movieCount
  } else if item is Song {
    ++songCount
  }
}

所以当我得到item时,item的类型是MediaItem

但为什么“item is Movie”将返回trun ??

因为Movie是MediaItem的子类

所以如果我得到MediaItem类型

应该写成“电影是项目”

Mean Movie是MediaItem的子类吗?

但为什么写“item is Movie”

1 个答案:

答案 0 :(得分:2)

看起来您在变量的类型与分配给变量的对象的类型之间存在差异。

也许这可能会给你一点见解:

let movie = Movie(name: "Casablanca", director: "Michael Curtiz")
var test : AnyObject = movie

println(test is Movie) // "true" since it's an instance of Movie
println(test is MediaItem) // "true" since Movie is a subclass of MediaItem
println(test is Song) // "false", it's not a Song.

// Assign to variable of type MediaItem works because Movie is
// a subclass of MediaItem
let item : MediaItem = movie

println(item is Movie) // "true" since the object really is a Movie
println((item as AnyObject) is MediaItem) // "true" since Movie is a subclass of MediaItem
println(item is Song) // "false", it's not a Song.

// The next line does NOT work: "upcasting" is not allowed.
// You will get a compiler error here.
let anotherMovie : Movie = item