下標


標籤

index 取值

var text = ["a", "b", "c", "d", "e"]
print(text[0])
print(text[3])
  • 輸出結果
    a
    d
    
    • index 從0 開始算起

key 取值

var number = ["a": "abcde", "b": "12345"]
print(number["a"])
  • 輸出結果
    Optional("abcde")
    

基本架構

  • 範例ㄧ
    subscript((名稱): (型別)) -> (返回型別) {
        return (返回值)
    }
    
    class data {
        var number = 100
        subscript(newdata: Int) -> Int {
            return number / newdata
        }
    }
    
    print(DATA.number)
    print(DATA[10])
    
    • 輸出結果
      100
      10
      
  • 範例二
    subscript((名稱): (型別)) -> (返回型別) {
        get {
            return (返回值)
        }
        set{
        }
    }
    
    class data {
        var number = 100
        subscript(newdata: String) -> Int {
            get {
                print(newdata)
                return number * 2
            }
            set {
                number *= newValue
            }
        }
    }
    
    let DATA = data()
    print(DATA["data"])
    DATA["data"] = 5
    print(DATA.number)
    
    • 輸出結果
      data
      200
      500
      

results matching ""

    No results matching ""