Swift 基础语法学习(三)

  • 类型别名 - Type Aliases
    作用:给一个已经存在的数据类型取一个别名,新创建的别名更加具有实际意义,可读性更强。和 OC 中的 typedef 作用一样,不过使用方式有些许不同。
    1. OC 中使用类型别名

    typedef 已经存在的数据类型 别名;
    /// 例子
    typedef NSInteger Amount;
    
    /// 使用类型别名声明一个变量
    @property(nonatomic, assign) Amount money;
    
    1. Swift 中使用类型别名
    /// Int 类型的别名为 Amount
    typealias Amount = Int
    
    /// 使用
    let money: Amount
    money = 100    
    
  • 布尔类型 - Bool
    Swift 中的基本数据类型之一,作为条件语句的结果。Bool 类型有两个常量值,分别是:truefalse

    let result: Bool
    let state = true
    let status = false
    
    /// Swift 中,if 语句的判断表达式中必须使用 Bool 类型的值
    if state {
    }
    
  • 元组类型 - Tuples (Swift 和 ObjC 的不同之一)
    可以将多个相同类型或者不同类型的值组合到一个整体中使用。

    /// 元组的声明
    /// 方式一:元组元素有名字
    let response = (code: 404, description: "Not Found")
    /// 方式二:元组元素没有名字
    let result = (404, "Not Found")
    
    /// 元组的使用
    let (resCode, resDesc) = result
    print(resCode)
    print(resDesc)
    /// 只声明一个元素
    let (code, _) = result
    print(code)
    let (_, desc) = result
    print(desc)
    
    /// 元组数据的进入
    /// 如果声明的时候有名字,那么可以使用元组的名字或者下标取值
    print(response.code) == print(response.0)
    print(response.description) == print(response.1)
    
    /// 如果声明的时候没有名字,那么只能使用元组的下标取值,注意元组下标从0开始
    print(result.0)
    print(result.1)
    

    注意:元组只适合存储简单的数据结构,不适合用于代表复杂数据结构。

你可能感兴趣的:(Swift 基础语法学习(三))