swift 对象转换_Swift类型转换–照原样,任何对象

本文介绍了Swift中的类型转换,包括类型检查、上播(Upcasting)、下垂(Downcasting)以及Any和AnyObject的用法。通过示例代码展示了如何在Swift中进行类型转换,并解释了它们在不同场景下的应用。
摘要由CSDN通过智能技术生成

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: String) {
        self.university = university
    }
}

class Discipline : University{
    var discipline: String
    init(university: String, discipline: String) {
        self.discipline = discipline
        super.init(university: university)
    }
}

class Student : University{
    var student: String
    init(student: String, university: String) {
        self.student = student
        super.init(university: university)
    }
}

In the following sections, we’ll be looking at Upcasting and Downcasting.

在以下各节中,我们将介绍上播和下播。

Swift上流 (Swift Upcasting)

Let’s create an object of each of the classes and combine them in an Array. Our goal is to know thy type!

让我们为每个类创建一个对象,并将它们组合到Array中 。 我们的目标是了解您的类型!

var array = [University(university: "MIT"),Discipline(university: "IIT",discipline: "Computer Science"),Student(student: "Anupam",university: "BITS")]

print(array is [Student])
print(array is [Discipline])
print(array is [University])

The following output is printed.

Swift Type Casting - Upcasting

打印以下输出。

The array is of the type University. All the subclasses are always implicitly upcasted to the parent class.

该数组是大学类型。 所有子类始终都隐式地转换为父类。

In the above code, the Swift Type Checker automatically determines the common superclass of the classes and sets the type to it.

在上面的代码中,Swift类型检查器自动确定类的公共超类并将其设置为类型。

type(of:) can be used to determine the type of any variable/constant.

type(of:)可用于确定任何变量/常量的类型。

var university = University(university: "MIT")
var student = Student(student: "Anupam",university: "BITS")
var discipline = Discipline(university: "IIT",discipline: "Computer Science")

print(student is University) //true
print(discipline is University) //true
print(university is Student) //false
print(university is Discipline) //false

Protocols are types. Hence type checking and casting works the same way on them.

协议是类型。 因此,类型检查和强制转换在它们上的工作方式相同。

The following code prints true.

以下代码显示为true。

protocol SomeProtocol {
    init(str: String)
    
}

class SomeClass : SomeProtocol {
    required init(str: String) {
    }
}

var sc = SomeClass(str: "JournalDev.com")
print(sc is SomeProtocol) //true

Swift下垂 (Swift Downcasting)

For downcasting a superclass to the subclass, we use the operator as.

为了将超类向下转换为子类,我们使用运算符as

  1. as has two variants, as? and as! to handle scenarios when the downcasting fails.

    有两个变体, as?as! 处理向下转换失败时的情况。
  2. as is typically used for basic conversions.

    通常用于基本转化。
  3. as? would return an optional value if the downcast succeeds and nil when it doesn’t.

    as? 如果下调成功,将返回一个可选值,否则将返回nil。
  4. as! force unwraps the value. Should be used only when you’re absolutely sure that the downcast won’t fail. Otherwise, it’ll lead to a runtime crash.

    as! 强行包装价值。 仅在绝对确定向下转换不会失败时才应使用。 否则,将导致运行时崩溃。
//Double to float
let floatValue = 2.35661312312312 as Float
print(float) //prints 2.35661

let compilerError = 0.0 as Int //compiler error
let crashes = 0.0 as! Int //runtime crash

Let’s look at the class hierarchy again. Let’s try to downcast the array elements to the subclass types now.

让我们再次看看类的层次结构。 让我们现在尝试将数组元素转换为子类类型。

var array = [University(university: "MIT"),
             Discipline(university: "IIT",discipline: "Computer Science"),
             Student(student: "Anupam",university: "BITS"),
             Student(student: "Mark",university: "MIT")]

for item in array {
    if let obj = item as? Student {
        print("Students Detail: \(obj.student), \(obj.university)")
    } else if let obj = item as? Discipline {
        print("Discipline Details: \(obj.discipline), \(obj.university)")
    }
}

We downcast the type University to the subclass types.
Following results get printed in the console.

Swift Type Casting - Downcasting

我们将大学类型简化为子类类型。
以下结果将打印在控制台中。

We’ve used if let statements to unwrap the optionals gracefully.

我们使用过if语句来优雅地解开可选部分。

Any和AnyObject (Any and AnyObject)

As per the Apple Docs:

根据Apple Docs:

Any can represent an instance of any type at all, including function types.
AnyObject can represent an instance of any class type.

Any可以代表任何类型的实例,包括函数类型。
AnyObject可以代表任何类类型的实例。

AnyObject can be a part of Any type.
Inside an AnyObject array, to set value types, we need to typecast them to the AnyObject using as operator.

AnyObject可以是Any类型的一部分。
在AnyObject数组内部,要设置值类型,我们需要使用as运算符将其类型转换为AnyObject。

class A{
    var a = "Anupam"
}
func hello()
{
    print("Hello")
}

var anyType : [Any] = [1, "Hey",array,true, 1.25, A(), hello()]
var anyObjectType : [AnyObject] = [A(),array as AnyObject, 1 as AnyObject,"Hey" as AnyObject]

print(anyType)
print(anyObjectType)

for item in anyType {
    if let obj = item as? A {
        print("Class A property name is: \(obj.a)")
    }
}

for item in anyObjectType {
        if let obj = item as? String {
            print("String type: \(type(of: obj))")
        }
}

The function that’s present in the anyType array, gets printed on the array’s declaration.

anyType数组中存在的函数会打印在数组的声明中。

Notice that for anyObjectType, the string gets printed without double quotes.

请注意,对于anyObjectType ,该字符串在打印时不带双引号。

Besides AnyObject allows object types only. String and Int are value types.

此外,AnyObject仅允许对象类型。 字符串和整数是值类型。

Then how is it working?.

那怎么运作呢?

On typecasting the string and int as AnyObject they both get converted into NSString and NSNumber class types which are not value types. Hence it is possible to set String, Int in AnyObject provided we use the as operator correctly.

在将字符串和int转换为AnyObject时,它们都将转换为非值类型的NSString和NSNumber类类型。 因此,只要我们正确使用as运算符,就可以在AnyObject中设置String,Int。

That’s all for swift type casting.

这就是快速类型转换的全部内容。

Reference: Apple Docs

参考: Apple Docs

翻译自: https://www.journaldev.com/19665/swift-type-casting-as-is-any

swift 对象转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值