is
is的功能相当于OC中的isKindOfClass,是否是这样某类的或者某类的子类的实例对象
as
1.向上转型,代码
class Person{}
class Programmer:Person{}
let pro = Programmer()
let p = pro as Person
2.数值类型转换
let num = 3 as Int
let num = 0.3 as CGFloat
3.switch语句中进行模式匹配
switch p{
case let teacher as Teacher:
print("是老师")
case let student as Student:
print("是学生")
default: break
}
as!
向下转型,代码
class Person{}
class Programmer:Person{}
let p:Person = Programmer()
let pro = p as! Programmer
将一个父类类型转成了一个子类类型,如果转换失败,运行时会报错
as?
和as!转换规则一样,但如果转换失败不会报错而是返回nil,转换成功返回一个可选类型。
网友评论