类型转换在 Swift 中使用 is
和 as
操作符实现,也可以用它来检查一个类型是否遵循了某个协议。
class Person {
var name:String
init(name:String) {
self.name = name
}
}
class Student: Person {
var id:Int = 10086
}
class Teacher: Person {
var job = "Teach"
}
// 数组类型:[Person]
var persons = [
Person.init(name: "人"),
Student.init(name: "生"),
Teacher.init(name: "师"),
Student.init(name: "生")
]
var studentCount = 0
var teacherCount = 0
var otherCount = 0
for item in persons {
if item is Student { // is 判断是否是这个类型
studentCount += 1
if let stu = item as? Student { // as? 向下转换类型
print("stu.id = \(stu.id)")
}
}else if item is Teacher {
teacherCount += 1
if let tea = item as? Teacher {
print("tea.id = \(tea.job)")
}
}else if item is Person{ // will always true
otherCount += 1
}
}
print("person = \(otherCount),student = \(studentCount),teacher = \(teacherCount)")
Any 和 AnyObject
-
Any
可以表示任何类型var things: [Any] = [] things.append(0)// 值类型 things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) // 函数类型 things.append({ (name: String) -> String in "Hello, \(name)" }) // 闭包类型
-
AnyObject
可以表示任何类类型的实例。
可以在
switch
表达式的case
中使用is
和as
操作符来找出只知道是Any
或AnyObject
类型的常量或变量的具体类型。
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
case is Double:
print("some other double value that I don't want to print")
case let someString as String:
print("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
print("an (x, y) point at \(x), \(y)")
case let movie as Movie:
print("a movie called \(movie.name), dir. \(movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("Michael"))
default:
print("something else")
}
}
Any
类型可以表示所有类型的值,包括可选类型。Swift 会在你用Any
类型来表示一个可选值的时候,给你一个警告。如果你确实想使用Any
类型来承载可选值,你可以使用as
操作符显式转换为Any
,如下所示:
let optionalNumber: Int? = 3
things.append(optionalNumber) // 警告
things.append(optionalNumber as Any) // 没有警告
网友评论