zoukankan      html  css  js  c++  java
  • Swift开发第五篇——四个知识点(Struct Mutable方法&Tuple&autoclosure&Optional Chain)

    本篇分三部分:

    一、Struct Mutable方法

    二、多元组(Tuple) 的使用

    三、autoclosure 的使用

    四、Optional Chain 的使用


    一、Struct Mutable方法

    直接上代码:

    struct User {
        var weight: Int
        var height: Int
        
        // 这里会报错 Left side of mutating operator isn't mutable:'self' is immutable
        // 因为 Struct 出来的变量是 immutable 的,想要用一个方法去改变变量里面的值的时候必须要加上一个关键字 mutating
        mutating func gainWeight(newWeight: Int) {
            weight += newWeight
        }
    }
    var newUser = User(weight: 117, height: 178)
    newUser.gainWeight(10)

    运行结果: 


    二、多元组(Tuple)

      多元组是 Swift 的新特性,普通程序员都是定义一个临时变量来保存需要交换的值得,现在我们可以不使用额外空间而使用多元组特性直接交换 a 和 b 的值

    func swapMe<T>(inout a: T, inout b: T) {
        (a, b) = (b, a)
    }
    var a = 5, b = 6
    swapMe(&a, b: &b)
    print(a, b)  // 输出结果为6 5

    三、autoclosure的 基本使用

    // 在不使用autoclosure的情况下
    func logIfTrue(predicate: () -> Bool) {
        if predicate() {
            print("True")
        }
    }
    // 第一种调用方式
    logIfTrue { () -> Bool in
        return true
    }
    // 第二种调用方式
    logIfTrue({return 2 > 1})
    // 第三种调用方式
    logIfTrue({2 > 1})
    // 第四种调用方式
    logIfTrue{2 > 1}
    
    // 使用autoclosure
    func logIfTrue(@autoclosure predicate: () -> Bool) {
        if predicate() {
            print("True")
        } else {
            print("False")
        }
    }
    // 调用方式
    logIfTrue(2 > 1)
    logIfTrue(1 > 2)

    四、Optional Chain 的使用

    class Toy {
        let name: String
        init(name: String) {
            self.name = name
        }
    }
    
    class Pet {
        var toy: Toy?
    }
    
    class Child {
        var pet: Pet?
    }
    
    let toy: Toy = Toy(name: "")
    let pet: Pet = Pet()
    let xiaoming: Child = Child()

      在这里最后访问的是 name,并且在 Toy 的定义中 name 是被定义为一个确定的 String 而非 String? 的,但是我们拿到的 toyName 其实还是一个 String?的类型。这是由于在 Optional Chaining 中我们在任意一个 ? 的时候都可能遇到 nil 而提前返回,这个时候当然就只能拿到 nil 了

    let toyName = xiaoming.pet?.toy?.name
    // 所以在实际开发中,我们通常使用 Optional Binding 来直接取值:
    if let toyName = xiaoming.pet?.toy?.name {
        // 这时toyName 就是 String 而非 String? 了
    }
    
    extension Toy {
        func play() {
            print("玩玩具~~")
        }
    }
    
    let playClosure = {(child: Child) -> () in
        child.pet?.toy?.play()
    }
  • 相关阅读:
    [CQOI2009]叶子的染色
    CF149D 【Coloring Brackets】
    [BJOI2016]回转寿司
    linux基础学习-19.2-Shell脚本的创建
    linux基础学习-19.1-Shell的介绍
    linux基础学习-18.11-第六关考试题
    linux基础学习-18.10-awk数组
    linux基础学习-18.9-awk中的动作
    linux基础学习-18.8-awk特殊模式-BEGIN模式与END模式
    linux基础学习-18.7-awk范围模式
  • 原文地址:https://www.cnblogs.com/Jepson1218/p/5283063.html
Copyright © 2011-2022 走看看