美文网首页Swift 相关
Swift 添加下标 subscript

Swift 添加下标 subscript

作者: xxxixxxx | 来源:发表于2020-10-12 14:20 被阅读0次

    关键子 subscript

    参数和返回值可以是任意类型(inout输入输出除外)

    struct People {
        var name = "", age = 0
    
    // 给实例添加下标
        subscript(n: String) -> Int {
            get {
                return age
            }
            set {
                age = newValue
            }
        }
    
    // 给结构体添加下标
        static subscript(name: String, age: Int) -> People {
            People(name: name, age: age)
        }
    }
    
    var a = People(name: "哈哈哈", age: 18)
    print(a["哈哈哈"])//18
    a["哈哈哈"] = 20
    print(a["哈哈哈"])//20
    let p = People["哈喽", 20]
    print(p)//People(name: "哈喽", age: 20)
    

    相关文章

      网友评论

        本文标题:Swift 添加下标 subscript

        本文链接:https://www.haomeiwen.com/subject/hzgupktx.html