swift 对象转换
In this tutorial, we’ll be looking into the details of Swift Type Casting. Let’s get started on our Xcode Playground!
在本教程中,我们将研究Swift Type Casting的细节。 让我们开始在我们的Xcode Playground!
什么是Swift类型转换? (What is Swift Type Casting?)
Broadly, Type Casting consists of two things:
大致来说,类型转换包含两件事:
- Type Checking 类型检查
- Changing the Type 改变类型
is
operator is used to check the type of an instance.is
运算符,用于检查实例的类型。as
operator is used to cast the instance to another type.as
运算符用于将实例转换为其他类型。
快速类型检查 (Swift Type Checking)
Swift gives a lot of priority to the readability of the code. No wonder to check whether an instance belongs to a certain type, we use the is
keyword.
Swift对代码的可读性给予了很多优先考虑。 难怪要检查实例是否属于某种类型,我们使用is
关键字。
For Example, the following code snippet would always print false.
例如,以下代码片段将始终显示false。
var isString = Int.self is String
print(isString) // false
Let’s do the type checking in the class and its subclasses. For that, we’ve created the following three classes.
让我们在类及其子类中进行类型检查。 为此,我们创建了以下三个类。
class University
{
var university: String
init(university