• Swift中的类型转换


    写在前面:1,类型转换的两种方式

      2,as!和as?的用法

      3,类型判断中 is和===的用法

    类型转换方式一,利用类型的构造器进行转换

    复制代码
    1 let str = "5"
    2 var i = Int(str)
    3 if(i == nil){
    4     print("变量i为nil不能进行运算")
    5 }else{
    6     //由于变量i是一个可为空的变量,因此需要强制解封
    7     let rs = i! + 1
    8     print("变量i进行运算后的结果为(rs)")
    9 }
    复制代码

    类型转换方式二,使用as?和as!进行转换

    复制代码
     1 class A {
     2     func am(){
     3         print("am method")
     4     }
     5 }
     6 class B: A {
     7     func bm() {
     8         print("bm method")
     9     }
    10 }
    11 class C {
    12 
    13 }
    14 
    15 let ins: A = B()
    16 let insb1 = ins as? B
    17 let insb2 = ins as! B
    18 
    19 //使用as?进行转换时,若转换失败则会返回nil
    20 if insb1 == nil {
    21     print("change failed..(insb1)")
    22 }else{
    23     print("change success")
    24     insb1?.am()
    25 }
    复制代码

    注意:使用as?进行转换时,若转换失败则会返回nil

    复制代码
     1 class A {
     2     func am(){
     3         print("am method")
     4     }
     5 }
     6 class B: A {
     7     func bm() {
     8         print("bm method")
     9     }
    10 }
    11 class C {
    12 
    13 }
    14 
    15 let ins: A = B()
    16 let insb1 = ins as? B
    17 let insb2 = ins as! B
    18 
    19 if insb2 == nil {
    20     //这个分支将永远不会被执行
    21     print("change failed..(insb2)")
    22 }else{
    23     print("change success")
    24     insb2.am()
    25 }
    复制代码

    注意:使用as!进行转换时,要么转换成功,若失败程序将会产生异常

    类型判断:is

    1 //判断的是两个对象的类型是否一致,因此下面代码if条件满足
    2 if ins is B  {
    3     print("is b")
    4 }

    类型判断:===

    复制代码
    1 //判断的是两个对象所引用的内存地址是否相同,因此下面代码无输出
    2 let ins3 = B()
    3 let ins4 = B()
    4 let ins5 = ins3
    5 if ins3 === ins4 {
    6     print("true...")
    7 }
    复制代码
  • 相关阅读:
    Leetcode Unique Binary Search Trees
    Leetcode Decode Ways
    Leetcode Range Sum Query 2D
    Leetcode Range Sum Query
    Leetcode Swap Nodes in Pairs
    Leetcode Rotate Image
    Leetcode Game of Life
    Leetcode Set Matrix Zeroes
    Leetcode Linked List Cycle II
    CF1321A
  • 原文地址:https://www.cnblogs.com/zhangyingai/p/7098968.html
Copyright © 2020-2023  润新知