Swift编程中的一些类型转换方法详解_Swift

验证一个实例的类型'类型转换'在 Swift 语言编程中。它是用来检查实例类型是否属于特定超类或子类或其自己的层次结构定义。

Swift 类型转换提供两个操作符:“is” 检查值的类型和 'as' 将类型值转换为不同的类型值。 类型转换还检查实例类型是否符合特定的协议一致性标准。

定义一个类层次结构
类型转换用于检查实例的类型或者它属于特定类型。此外,检查类和它的子类层次结构来检查并转换这些实例,使之作为一个相同的层次结构。

复制代码 代码如下:

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: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
println("Instance physics is: \(samplechem.physics)")
println("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
println("Instance physics is: \(samplemaths.physics)")
println("Instance formulae is: \(samplemaths.formulae)")

当我们使用 playground 运行上面的程序,得到以下结果。

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz

类型检查
进行类型检查,用 'is' 操作符。在 'is' 操作符检查类型实例是否属于特定的子类型,如果它属于该实例返回“true”,否则将返回“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: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
println("Instance physics is: \(samplechem.physics)")
println("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
println("Instance physics is: \(samplemaths.physics)")
println("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0
for item in sa {
   if item is Chemistry {
      ++chemCount
   } else if item is Maths {
      ++mathsCount
   }
}

println("Subjects in chemistry contains \(chemCount) topics and maths contains \(mathsCount) topics")

当我们使用 playground 运行上面的程序,得到以下结果。

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Subjects in chemistry contains 2 topics and maths contains 3 topics

向下转换
向下类型转换的子类型可以有两个操作符(如:as? 和 as!)。as? 当值是nil,返回一个可选值。它是用来检查成功向下转型。

“as!” 返回强制解包裹,如可选链,向下转换返回 nil 值。它用来触发运行时错误在向下转型出现故障时

复制代码 代码如下:

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: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
println("Instance physics is: \(samplechem.physics)")
println("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
println("Instance physics is: \(samplemaths.physics)")
println("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in sa {
   if let print = item as? Chemistry {
      println("Chemistry topics are: '\(print.physics)', \(print.equations)")
   } else if let example = item as? Maths {
      println("Maths topics are: '\(example.physics)',  \(example.formulae)")
   }
}

当我们使用 playground 运行上面的程序,得到以下结果。

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series

类型转换:任何与任何对象
为了表示实例属于任何类型包括函数类型,使用“Any”关键字

复制代码 代码如下:

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: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
println("Instance physics is: \(samplechem.physics)")
println("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
println("Instance physics is: \(samplemaths.physics)")
println("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in sa {
   if let print = item as? Chemistry {
      println("Chemistry topics are: '\(print.physics)', \(print.equations)")
   } else if let example = item as? Maths {
      println("Maths topics are: '\(example.physics)',  \(example.formulae)")
   }
}

var exampleany = [Any]()

exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Example for Any")
exampleany.append(Chemistry(physics: "solid physics", equations: "Hertz"))

for print in exampleany {
   switch print {
   case let someInt as Int:
      println("Integer value is \(someInt)")
   case let someDouble as Double where someDouble > 0:
      println("Pi value is \(someDouble)")
   case let someString as String:
      println("\(someString)")
   case let phy as Chemistry:
      println("Topics '\(phy.physics)', \(phy.equations)")
   default:
      println("None")
   }
}

当我们使用 playground 运行上面的程序,得到以下结果。

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz
AnyObject

为了表示是任何类型的类实例,使用AnyObject“关键字

复制代码 代码如下:

 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 saprint: [AnyObject] = [Chemistry(physics: "solid physics", equations: "Hertz"),
   Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
   Chemistry(physics: "Thermo physics", equations: "Decibels"),
   Maths(physics: "Astro Physics", formulae: "MegaHertz"),
   Maths(physics: "Differential Equations", formulae: "Cosine Series")]

let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
println("Instance physics is: \(samplechem.physics)")
println("Instance equation is: \(samplechem.equations)")

let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
println("Instance physics is: \(samplemaths.physics)")
println("Instance formulae is: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in saprint {
   if let print = item as? Chemistry {
      println("Chemistry topics are: '\(print.physics)', \(print.equations)")
   } else if let example = item as? Maths {
      println("Maths topics are: '\(example.physics)',  \(example.formulae)")
   }
}

var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Example for Any")
exampleany.append(Chemistry(physics: "solid physics", equations: "Hertz"))

for print in exampleany {
   switch print {
   case let someInt as Int:
      println("Integer value is \(someInt)")
   case let someDouble as Double where someDouble > 0:
      println("Pi value is \(someDouble)")
   case let someString as String:
      println("\(someString)")
   case let phy as Chemistry:
      println("Topics '\(phy.physics)', \(phy.equations)")
   default:
      println("None")
   }
}

当我们使用 playground 运行上面的程序,得到以下结果。

Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索swift
swift报文类型详解、swift强制类型转换、swift 类型转换、swift3 类型转换、swift3.0 类型转换,以便于您获取更多的相关知识。

时间: 2024-10-24 21:02:54

Swift编程中的一些类型转换方法详解_Swift的相关文章

Swift语言中的一些访问控制设置详解_Swift

限制访问代码块,模块和抽象通过访问控制来完成.类,结构和枚举可以根据自己的属性,方法,初始化函数和下标来通过访问控制机制进行访问.常量,变量和函数的协议限制,并允许通过访问控制来访问全局和局部变量.应用于属性,类型及函数的访问控制可以被称为"实体". 访问控制模型是基于模块和源文件的. 模块定义为代码分配一个单独的单元,并且可以使用import 关键字导入.源文件被定义为一个单一的源代码文件,模块可访问多种类型和函数. 三种不同的访问级别是由 Swift 语言提供.它们分别是 Publ

Node.js编程中客户端Session的使用详解

  这篇文章主要介绍了Node.js编程中客户端Session的使用详解,是Node.js入门学习中的基础知识,需要的朋友可以参考下 静态网站很容易扩展.你只需要全部缓存,不需要考虑从不同服务器组合有状态的内容给用户. 可惜,大多数Web应用使用有状态的内容提供个性化体验.如果你的应用可以登录,就需要记住用户的Session.经典的处理方法是客户端设置包含随机唯一Session标识的Cookie,被标识的Session数据保存到服务端. 扩展有状态服务 当扩展服务的时候,你肯定有三种选择: 不同

PHP编程中的__clone()方法使用详解_php技巧

可以在对象类中定义一个__clone()方法来调整对象的克隆行为.此方法的代码将在克隆操作期间执行.除了将所有现有对象成员复制到目标对象之外,还会执行__clone()方法指定的操作.下面修改Corporate_Drone类,增加以下方法: function __clone() { $this->tiecolor = "blue"; } 之后,创建一个新的Corporate_Drone对象,增加employeeid成员的值,克隆这个对象,然后输出一些数据,从而显示克隆对象的tie

浅谈Swift编程中switch与fallthrough语句的使用_Swift

在 Swift 中的 switch 语句,只要第一个匹配的情况(case) 完成执行,而不是通过随后的情况(case)的底部,如它在 C 和 C++ 编程语言中的那样.以下是 C 和 C++ 的 switch 语句的通用语法: 复制代码 代码如下: switch(expression){    case constant-expression  :       statement(s);       break; /* optional */    case constant-expressio

Android编程中的消息机制实例详解_Android

本文实例讲述了Android编程中的消息机制.分享给大家供大家参考,具体如下: 在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListener { private TextView stateText; private Button btn; @Override public void onCreate(Bundle savedInstanceState)

Android编程中context及全局变量实例详解_Android

本文实例讲述了Android编程中context及全局变量的用法.分享给大家供大家参考,具体如下: 今天在研究context的时候,对application和activity context有了一定的了解,下面是从网上复制过来的资料 Application context和Activity context的区别: 这是两种不同的context,也是最常见的两种.第一种中context的生命周期与Application的生命周期相关的,context随着Application的销毁而销毁,伴随ap

Android编程中的消息机制实例详解

本文实例讲述了Android编程中的消息机制.分享给大家供大家参考,具体如下: 在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListener { private TextView stateText; private Button btn; @Override public void onCreate(Bundle savedInstanceState)

Android编程中光线传感器的调用方法详解

本文实例讲述了Android编程中光线传感器的调用方法.分享给大家供大家参考,具体如下: 1.activity如果要使用传感器,就必须实现SensorEventListener接口 2.得到传感器管理对象(sensormanager) 3.使用sensormanager.registerlistener 方法注册指定的传感器 4.在sensoreventlistener 接口中的onsensorchanged和onaccuracychanged方法中完成其他具体工作 public class T

详解Swift编程中的方法与属性的概念_Swift

方法在 Swift 中特定类型的相关联功能被称为方法.在 Objective C 中类是用来定义方法,其中作为 Swift 语言为用户提供了灵活性,类,结构和枚举中可以定义使用方法. 实例方法 在 Swift 语言,类,结构和枚举实例通过实例方法访问. 实例方法提供的功能 访问和修改实例属性 函数关联实例的需要 实例方法可以写在花括号 {} 内.它隐含的访问方法和类实例的属性.当该类型指定具体实例它调用获得访问该特定实例. 语法 复制代码 代码如下: func funcname(Paramete