關(guān)于swift的枚舉
一 swift對于枚舉的擴展性(Enum
)
- 枚舉的繼承(繼承任何類和協(xié)議浦箱,目前除了swift協(xié)議中
@objc
無法繼承,oc和swift不兼容的原因之一)
@objc protocol LabelStatus {
@objc func labelStatus()
}
//Non-class type 'LabelState' cannot conform to class protocol 'LabelStatus'
//extension LabelState: LabelStatus {
//
}
- 枚舉繼承String(使用rawValue可以獲取值)
case none = ""
case loading = "loading"
case success = "success"
case failure = "failure"
}
extension LabelState: Hashable {
var stateStr: String {
switch self {
case .failure:
return "failure"
default:
return "default"
}
}
}
- 枚舉實現(xiàn)
Comparable
協(xié)議
// 關(guān)于(Comparable) 比較====> 相當于比較hashValue,
extension LabelState: Comparable {
static func < (lhs: LabelState, rhs: LabelState) -> Bool {
return lhs.hashValue < rhs.hashValue
}
static func ==(lhs: LabelState, rhs: LabelState) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
- 枚舉的高級用法(使用枚舉來解析數(shù)據(jù)源)
private enum KeyType: String {
case content; case image; case chooseType; case none
}
/// 這里面content中可以繼續(xù)通過枚舉值解析
/// 例子
/// content(JsonType)
case content(JSON)
case image(LINK)
case type(ChooseType)
case none
init?(json: JSON) {
guard let conentType = json["type"] as? String else {fatalError("error json key value")}
let keyType = KeyType(rawValue: conentType)
switch keyType {
case .content?:
self = .content(json)
case .image?:
guard let link = json["link"] as? String else {fatalError("don't contain key image")}
self = .image(link)
case .chooseType?:
guard let chooseType = json["value"] as? Bool else {fatalError("don't contain key value")}
self = .type(chooseType ? .select : .deselect)
default:
return nil
}
return nil
}
}
- 使用枚舉類細化
JSON
的內(nèi)部結(jié)構(gòu)滑凉,通過顯示cell的邏輯分化代碼結(jié)構(gòu)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataParser?.cellTypes.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let type = dataParser!.cellTypes[indexPath.row]
let cell: UITableViewCell
switch type {
case .content(let json):
cell = tableView.dequeueReusableCell(withIdentifier: ContentCell.identifier, for: indexPath)
(cell as! ContentCell).title.text = (json["msg"] as? String)
(cell as! ContentCell).title.sizeToFit()
case .image(let link):
cell = tableView.dequeueReusableCell(withIdentifier: ImageCell.identifier, for: indexPath)
let data = try? Data(contentsOf: URL(string: link)!)
(cell as! ImageCell).icon.image = UIImage(data: data!)
case .type(let type):
cell = tableView.dequeueReusableCell(withIdentifier: CommonCell.identifier, for: indexPath)
(cell as! CommonCell).mySwitch.isOn = (type == .select) ? true : false
default:
cell = UITableViewCell()
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
*代碼地址代碼