Swift中的as as? as!
Swift是一门强类型语言,而Objective-C是弱类型语言(OC是动态性语言,让程序可以在运行时判断和决定其该有的行为,所以OC属于弱类型)。所以使用时需要注意对象之间关系,用is as as? as! 这些操作符来处理对象之间关系 本篇文章学习自泊学(boxueio.com) 类型的判断 - is
class Shape {}
class Rectangle: Shape {}
class Circle: Shape {}
let r = Rectangle()
let c = Circle()
let shapeArr: Array<Shape> = [r,c]
// 统计arr中各种形状的数量 is操作符; 用 A is B 这样的用法来判断对象类型
var totalRects: Int = 0
var totalCircles:Int = 0
shapeArr[0] is Rectangle
for s in shapeArr
{
if s is Rectangle
{
// ++totalRects
totalRects += 1
}else if s is Circle{
totalCircles += 1
}
}
此时totalRects和totalCircles打印结果均为1 类型转换 - as? as!
shapeArr[0] as? Rectangle
shapeArr[0] as! Rectangle
shapeArr[0] as? Circle
// shapeArr[0] as! Circle // error
在playground可以看到 此时分别输出: Optional<Rectangle>
Rectangle
nil
// 把示例 - 1 中的shapeArr该成:
let shapeArr: Array<AnyObject> = [r,c]
此时后面的转换依然成立 let rect = r as Rectangle // 如果此时用as!则会警告 forced cast of 'Rectangle' to same type has no effect
③ as可以直接用在switch case语句里,可以直接把对象转换成目标类型。相当于as! let box: Array<Any> = [ // Any, 表示任意一种类型
3,3.14,"3.1415",r,{ return "I'm a closure" }
]
closure是一个类型,不是对象,所以用Any,不用AnyObject for item in box
{
switch item
{
case is Int: // ①
print("(item) is Int")
case is Double:
print("(item) is Double")
case is String:
print("(item) is String")
case let rect as Rectangle: // ②
print("(rect)")
print("(item) is Rectangle")
case let fn as () -> String:
fn()
default:
print("out of box")
}
}
注释: protocol 与 is as as!as?除了转换Any和AnyObject之外,is和as还可以用来判断某个类型是否遵从protocol的约定
box[0] is Shape
此时值为
box[3] as? Shape
type(of: (box[3] as? Shape))
type(of: (box[3] as! Shape))
box[3] as! Shape
c as Shape
在playground看到,此时值分别为: Rectangle
Optional<Shape>.Type
Rectangle.Type
Rectangle
Circle
由此可以看出:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |