Swift Type Casting
Swift language type casting can determine the type of an instance. It can also be used to check whether an instance type belongs to an instance of its parent class or subclass.
In Swift, type casting is implemented using the `is` and `as` operators. `is` is used to check the type of a value, and `as` is used to cast the type.
Type casting can also be used to check whether a class conforms to a protocol.
Defining a Class Hierarchy
The following defines three classes: Subjects, Chemistry, and Maths. Chemistry and Maths inherit from Subjects.
The code is as follows:
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")
When the above program is executed, the output is:
Example physics is: solid state physics Example equation: Hertz Example physics is: fluid dynamics Example formula is: gigahertz
Checking Type
Type casting is used to check whether an instance type belongs to a specific instance type.
You can use it on class and subclass hierarchies to check the type of a particular class instance and cast that class instance to another type within the hierarchy.
Type checking uses theiskeyword.
operatoristo check whether an instance belongs to a specific subtype. If the instance belongs to that subtype, the type checking operator returns true; otherwise, it returns false.
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
// 如果是一个 Chemistry 类型的实例,返回 true,相反返回 false。
if item is Chemistry {
++chemCount
} else if item is Maths {
++mathsCount
}
}
print("化学科目包含 \(chemCount) 个主题,数学包含 \(mathsCount) 个主题")
When the above program is executed, the output is:
实例物理学是: 固体物理 实例方程式: 赫兹 实例物理学是: 流体动力学 实例公式是: 千兆赫 化学科目包含 2 个主题,数学包含 3 个主题
Downcasting
Downcasting is done using the type cast operator (as? or as!)
When you are unsure whether downcasting will succeed, use the conditional form of type casting (as?). The conditional form of type casting always returns an optional value, and if the downcast is not possible, the optional value will be nil.
Only use the forced form (as!) when you are certain the downcast will succeed. If you try to downcast to an incorrect type, the forced form of type casting will trigger a runtime error.
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}
When the above program is executed, the output is:
Example physics is: solid state physics Example equation: Hertz Example physics is: fluid dynamics Example formula is: gigahertz Chemistry topic is: 'solid state physics', Hertz Mathematics topic is: 'fluid dynamics', gigahertz Chemistry topic is: 'thermal physics', decibel Mathematics topic is: 'astrophysics', megahertz Mathematics topic is: 'differential equations', cosine series
Type Casting for Any and AnyObject
Swift provides two special type aliases for non-specific types:
AnyObjectIt can represent an instance of any class type.AnyIt can represent any type, including function types.
Note:
Only use it when you explicitly need its behavior and functionalityAnyandAnyObject. It is always better to use the explicit type you expect in your code.
Any Instance
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}
// 可以存储Any类型的数组 exampleany
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 实例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))
for item2 in exampleany {
switch item2 {
case let someInt as Int:
print("整型值为 \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi 值为 \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("主题 '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}
When the above program is executed, the output is:
实例物理学是: 固体物理 实例方程式: 赫兹 实例物理学是: 流体动力学 实例公式是: 千兆赫 化学主题是: '固体物理', 赫兹 数学主题是: '流体动力学', 千兆赫 化学主题是: '热物理学', 分贝 数学主题是: '天体物理学', 兆赫 数学主题是: '微分方程', 余弦级数 整型值为 12 Pi 值为 3.14159 Any 实例 主题 '固体物理', 兆赫
AnyObject Instance
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}
class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}
class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}
// [AnyObject] 类型的数组
let saprint: [AnyObject] = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in saprint {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 实例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))
for item2 in exampleany {
switch item2 {
case let someInt as Int:
print("整型值为 \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi 值为 \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("主题 '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}
When the above program is executed, the output is:
实例物理学是: 固体物理 实例方程式: 赫兹 实例物理学是: 流体动力学 实例公式是: 千兆赫 化学主题是: '固体物理', 赫兹 数学主题是: '流体动力学', 千兆赫 化学主题是: '热物理学', 分贝 数学主题是: '天体物理学', 兆赫 数学主题是: '微分方程', 余弦级数 整型值为 12 Pi 值为 3.14159 Any 实例 主题 '固体物理', 兆赫
In a switch statement's case, use the forced form of the type cast operator (as, rather than as?) to check and convert to a specific type.
Other Extensions