將 UIKit segmented control 的內容定義成 enum raw value

開發 iOS App 時,我們時常使用 segmented control 選擇分類,比方下圖免費 App & 付費 App 的排行榜切換。

點選 segmented control 時,我們可以透過 selectedSegmentIndex 判斷使用者點選的分類,切換顯示不同的排行榜。

@IBAction func changeTopApps(_ sender: UISegmentedControl) {

switch sender.selectedSegmentIndex {
case 0:
print("show free apps")
case 1:
print("show paid apps")
default:
break
}
}

不過以上使用 switch 判斷數字的寫法較不直覺,無法一眼看出 0 & 1 的意思。我們可以有更好的寫法,將 segmented control 的內容定義成 raw value 型別為 Int 的 enum。

定義 segmented control 內容對應的 enum,raw value 型別為 Int

定義 AppCategory,raw value 型別為 Int。因此 free 的 raw value 為 0,paid 的 raw value 為 1,剛好對應 selectedSegmentIndex 的數字。

enum AppCategory: Int {
case free, paid
}

點選 segmented control 時比對 enum 型別的 AppCategory

利用 selectedSegmentIndex 當 raw value 生成 AppCategory,然後以 switch 比對 AppCategory。

@IBAction func changeTopApps(_ sender: UISegmentedControl) {

let appCategory = AppCategory(rawValue: sender.selectedSegmentIndex)!
switch appCategory {
case .free:
print("show free apps")
case .paid:
print("show paid apps")
}
}

Cool,現在我們實現了一樣的功能,但是程式變得更容易維護,更加清楚易懂了。

其它範例

Develop in Swift Data Collections 的 Lesson 3.2 Swift Generics Lab Morse Code。

定義 enum PlayerMode。

enum PlayerMode: Int {
case both, haptic, visual
}

點選 segmented control 時比對 enum 型別的 PlayerMode。

@IBAction func playerModeSegmentedControlValueChanged(_ sender: UISegmentedControl) {
let mode = PlayerMode(rawValue: sender.selectedSegmentIndex)!
configurePlayers(mode: mode)
}

func configurePlayers(mode: PlayerMode) {
switch (mode, hapticsPlayer) {
case (.haptic, let hapticsPlayer?):
activeMorseCodePlayers = [hapticsPlayer]
case (.both, let hapticsPlayer?) :
activeMorseCodePlayers = [hapticsPlayer, visualPlayerView]
default:
activeMorseCodePlayers = [visualPlayerView]
}
}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com