swift中的下標subscripts的用法,除了常規array, dictionay 根據key值獲取value外。
可以read and write, 可以讀也可以寫
subscript
(index:
int)
->
intset
(newvalue)
}
唯讀模式
subscript
(index:
int)
->
int
還可以定製get和set,腦洞比較大的地方在於物件也可以設定下標。比如下面的**,定製了下標的get方法,返回乙個乘積的結果。
struct
timestable
}let threetimestable =
timestable
(multiplier:3)
print
("six times three is \(threetimestable[6]
)")// prints "six times three is 18"
更大的腦洞在於,校驗物件的init值,比如下面的矩陣可以校驗是否越界
如上所述,例項下標是您在特定型別的例項上呼叫的下標。您還可以定義在型別本身上呼叫的下標。這種下標稱為型別下標。您可以通過在static關鍵字之前寫入關鍵字來指示型別下標subscript。類可以改用class關鍵字,以允許子類覆蓋該下標的超類實現。以下示例顯示了如何定義和呼叫型別下標:
enum
planet
:int
}let mars =
planet[4
]print
(mars)
// print mars
swift5基礎語法
先從最基本的常量 變數說起 新建變數 新建變數的語法 var keyword 變數名 資料型別 變數值 swift會自動判斷型別,所以資料型別可以省略 var str hello,playground print str var greeting hello swift developers pri...
Swift 5 可選型別 Optionals
var name string?jack var age int?age 10var age1 int?age1 age1 10age1 確定可選性不為空的時候才可以強制解包if let num int 123 num 0else a b a 是可選項 b 是可選或者不是可選 a和b的儲存型別必須相...
swift5入門練手走起
言歸正傳 今年吸取了教訓,先把基礎打牢,系統的學習一下swift5的語法和開發技能,先寫個練手demo開始。第二步 熟悉swift5的語法 第三步 策劃一款小遊戲 石頭剪子布 自導自研 第四步 show me the code 1 新建乙個viewcontroller.swift類,用於控制main...