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: Stringinit(university: String) {self.university = university}
}class Discipline : University{var discipline: Stringinit(university: String, discipline: String) {self.discipline = disciplinesuper.init(university: university)}
}class Student : University{var student: Stringinit(student: String, university: String) {self.student = studentsuper.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.

打印以下输出。

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.35661let 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.

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

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 对象转换

swift 对象转换_Swift类型转换–照原样,任何对象相关推荐

  1. php7对象转换成数组,php 如何把对象转换成数组对象

    php把对象转换成数组对象的方法:首先打开相应的PHP代码文件:然后通过"function array_to_object($arr){...}"方法把对象转换成数组即可. 本文操 ...

  2. jquery html对象 转换成字符串,JQuery - 将'HTMLDivElement'对象数组转换为字符串

    我过滤页面上的元素,然后检查显示的项目数,如果少于一定数量,我想使用$ .get()加载更多项目.JQuery - 将'HTMLDivElement'对象数组转换为字符串 我正在使用同位素插件,它要求 ...

  3. 将Model对象转换成json文本或者json二进制文件

    将Model对象转换成json文本或者json二进制文件 https://github.com/casatwy/AnyJson 注意:经过测试,不能够直接处理字典或者数组 主要源码的注释 AJTran ...

  4. python 对象转换为json_Python Python对象转换成JSON

    1.从Python对象转换成JSON 如果有Python对象,则可以使用json.dumps()方法将其转换为JSON字符串. 例如: 从Python对象转换为JSON:import json # a ...

  5. java 类之间转换,java中类对象之间的类型转换

    类似于基本数据类型之间的强制类型转换. 存在继承关系的父类对象和子类对象之间也可以 在一定条件之下相互转换. 这种转换需要遵守以下原则: 1.子类对象可以被视为是其父类的一个对象 2.父类对象不能被当 ...

  6. swift 听筒模式_Swift中的存储库模式

    swift 听筒模式 重点 (Top highlight) 背景 (Background) All apps developed require data of some description. T ...

  7. android 中XML和对象转换利器Xstream的使用

    XStream框架: 虽说pull dom dom4j等优秀的xml解析工具使用非常广泛,但对于复杂庞大的数据交互来说,使用它们无疑让你倍加痛苦,你可能大部分精力都放在无聊繁琐的解析和拼装上,如果接口 ...

  8. json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值...

    json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值 原文:json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值 主要内容: 一 ...

  9. 浅析Java中对象的创建与对象的数据类型转换

    这篇文章主要介绍了Java中对象的创建与对象的数据类型转换,是Java入门学习中的基础知识,需要的朋友可以参考下 Java:对象创建和初始化过程 1.Java中的数据类型     Java中有3个数据 ...

最新文章

  1. csr_matrix矩阵用法小结
  2. python读数据-python中如何读入数据
  3. OracleJDBC
  4. CF510C Fox And Names——拓扑排序练习
  5. 666!让移动端也用上3D·VR特效
  6. Colaboratory下载Kaggle数据
  7. 陕西专科学校王牌计算机专业,陕西省高职专科院校排名+王牌专业
  8. wordpress表单数据验证_实战:Drupal迁移到WordPress
  9. clion开发php,如何在 Mac 上用 Clion 调试 php7 源码
  10. 《程序设计技术》第一章例程
  11. python请输入星期几的第一个_python如何获取星期几
  12. 小刘的BUG(sql注入)
  13. builder设计模式,写和很好
  14. Java读取文件夹下的文件并进行处理
  15. org.apache.ibatis.binding.BindingException: Type interface com.java.mapper.UserMapper is not known t
  16. Constructing Narrative Event Evolutionary Graph for Script Event Prediction
  17. Java输出书名,输入书名 输出该书的信息 中java程序怎么设计
  18. 2020多益网络游戏开发工程师笔试
  19. 比周黑鸭与绝味食品更早上市的煌上煌,为何掉队了?
  20. origin2021导出图片时有水印解决

热门文章

  1. [转载] python通过反射执行代码
  2. 生成随机验证码,上传图片文件,解析HTML
  3. Qt QMutexLocker_自动解锁的机制
  4. ubuntu 環境下 bochs 的安裝
  5. url请求特殊字符转换
  6. python3,进程间的通信
  7. 【转】高并发情况下的单例模式
  8. asp.net 将ppt,word转化为pdf实现在线浏览详解
  9. Scala学习笔记(二)表达式和函数
  10. JS闭包中未使用的引用变量回收机制浅探