大佬教程收集整理的这篇文章主要介绍了[swift] is & as、Any & AnyObject,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
是用于swift 的类型检测
用简单的话来说就是:
class FatherClass {
var name: String
init(name: String) {
self.name = name
}
}
class SubClassA: FatherClass {
var proa: String
init(name: String,proa: String) {
self.proa = proa
super.init(name: Name)
}
}
class SubClassB: FatherClass {
var proB: String
init(name: String,proB: String) {
self.proB = proB
super.init(name: Name)
}
}
let Dic = [
SubClassA(name: "One",proa: "A pro one"),SubClassA(name: "Two",proa: "A pro two"),SubClassB(name: "Three",proB: "B pro one"),SubClassA(name: "Four",proa: "A pro three"),SubClassA(name: "Five",proa: "A pro four")
]
for item in Dic {
if item is SubClassA {
print("\(item.Name) is SubClassA")
} else if item is SubClassB {
print("\(item.Name) is SubClassB")
}
}
//One is SubClassA
//Two is SubClassA
//Three is SubClassB
//Four is SubClassA
//Five is SubClassA
for item in Dic {
if let subClassA = item as? SubClassA {
print("SubClassA: '\(subClassA.Name)',proa. \(subClassA.proa)")
} else if let subClassB = item as? SubClassB {
print("SubClassB: '\(subClassB.Name)',proB. \(subClassB.proB)")
}
}
//SubClassA: 'One',proa. A pro one
//SubClassA: 'Two',proa. A pro two
//SubClassB: 'Three',proB. B pro one
//SubClassA: 'Four',proa. A pro three
//SubClassA: 'Five',proa. A pro four
两种不确定类型
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(SubClassA(name: "Six",proa: "A pro five"))
things.append(SubClassB(name: "Seven",proB: "B pro two"))
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 subClassA as SubClassA:
print("a subclass called '\(subClassA.Name)',proa. \(subClassA.proa)")
case let subClassB as SubClassB:
print("a subclass called '\(subClassB.Name)',proB. \(subClassB.proB)")
default:
print("something else")
}
}
//zero as an Int
//zero as a Double
//an Integer value of 42
//a positive double value of 3.14159
//a String value of "Hello"
//an (x,y) point at 3.0,5.0
//a subclass called 'Six',proa. A pro five
//a subclass called 'Seven',proB. B pro two
以上是大佬教程为你收集整理的[swift] is & as、Any & AnyObject全部内容,希望文章能够帮你解决[swift] is & as、Any & AnyObject所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。