๐ŸŽ iOS & Swift

Enum์„ ํ™œ์šฉํ•ด TableViewController ๊ตฌ์„ฑํ•˜๊ธฐ

taeeekki 2022. 7. 19. 10:33

์šฐ์ธก ํ™”๋ฉด์„ ์–ด๋–ป๊ฒŒ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ์„๊นŒ? ๊ฐ„๋‹จํ•˜๊ฒŒ TableViewController๋ฅผ ์ด์šฉํ•ด๋ณด๋„๋ก ํ•˜์ž.


๋“ค์–ด๊ฐ€๊ธฐ ์ „์— ์‚ฌ์šฉํ•œ ํ”„๋กœํ† ์ฝœ์„ ๊ฐ„๋‹จํ•˜๊ฒŒ ์†Œ๊ฐœํ•˜๊ฒ ๋‹ค.

CaseIterable

์—ด๊ฑฐํ˜•์„ ๋ฐฐ์—ด์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์ฃผ๋Š” ํ”„๋กœํ† ์ฝœ

CustomStringConvertible

์•„๋ž˜ ๋งํฌ ์ฐธ๊ณ 
[Swift] CustomStringConvertible

ํ•œ๊ฐ€์ง€ ์ƒˆ๋กœ ์•Œ๊ฒŒ๋œ ๊ฒƒ์€ CustomStringConvertible ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•˜๊ณ , ์ถœ๋ ฅ์„ ํ•˜๋ฉด description์œผ๋กœ ์ •ํ•ด ๋†“์€ String ๊ฐ’์œผ๋กœ ์ถœ๋ ฅ๋˜๊ธธ๋ž˜ ๊ทธ ๋™์•ˆ Type ์—ญ์‹œ String์ธ ์ค„ ์•Œ์•˜์ง€๋งŒ Type์€ ๊ทธ๋Œ€๋กœ ์—ด๊ฑฐํ˜• ํƒ€์ž…์ด์—ˆ๋‹ค. print(SettingType.total)์™€ ๊ฐ™์ด ์ถœ๋ ฅ์„ ํ•˜๋ฉด "์ „์ฒด ์„ค์ •"๊ณผ ๊ฐ™์ด ์ถœ๋ ฅ๋˜๋Š”๋ฐ ์ด๋ฅผ ํ—ค๋”์˜ ํƒ€์ด๋ฅผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์—ˆ๋˜ ์ด์œ ๋Š” String ํƒ€์ž…์ด ์•„๋‹ˆ๋ผ ์—ด๊ฑฐํ˜• ํƒ€์ž…์ด์—ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๊ทธ๋ž˜์„œ String์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ฃผ์–ด์„œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์˜€๋‹ค.

// ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ธ์Šคํ„ด์Šค ๋ฉ”์„œ๋“œ๋„ ์žˆ๋”๋ผ.
String(describing: <#T##CustomStringConvertible#>)

๋‚˜์˜ ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์„œ ์œ„์˜ ํ™”๋ฉด์„ ๊ตฌํ˜„ํ–ˆ๋‹ค.

import UIKit

enum SettingType: CaseIterable, CustomStringConvertible {
    case total
    case personal
    case etc

    var contents: [String] {
        switch self {
        case .total:
            return ["๊ณต์ง€์‚ฌํ•ญ", "์‹คํ—˜์‹ค", "๋ฒ„์ „ ์ •๋ณด"]
        case .personal:
            return ["๊ฐœ์ธ/๋ณด์•ˆ", "์•Œ๋ฆผ", "์ฑ„ํŒ…", "๋ฉ€ํ‹ฐํ”„๋กœํ•„"]
        case .etc:
            return ["๊ณ ๊ฐ์„ผํ„ฐ/๋„์›€๋ง"]
        }
    }
    
    var numberOfRowInSections: Int {
        return contents.count
    }
    
    var description: String {
        switch self {
        case .total:
            return "์ „์ฒด ์„ค์ •"
        case .personal:
            return "๊ฐœ์ธ ์„ค์ •"
        case .etc:
            return "๊ธฐํƒ€"
        }
    }
}

final class SettingViewController: UITableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return SettingType.allCases.count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return String(describing: SettingType.allCases[section])
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return SettingType.allCases[section].numberOfRowInSections
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell") else { return UITableViewCell() }
        cell.textLabel?.text = SettingType.allCases[indexPath.section].contents[indexPath.row]
        return cell
    }
}