enum 水果 {case 櫻桃(價位: Int, 產地: String)case 火龍果(價位: Int, 產地: String)static let 價目表 = [櫻桃(價位: 3400, 產地: "華盛頓"),火龍果(價位: 1100, 產地: "埔里")]private func valueAt(pos: Int) -> AnyObject? {if let first = Mirror(reflecting: self).children.first {let children = Mirror(reflecting: first.value).childrenlet index = children.startIndex.advancedBy(IntMax(pos))if let value = children[index].value as? AnyObject {return value}}return nil}func 價位() -> Int {if let value = valueAt(0) as? Int {return value}return 0}private func valueAt(pos: Int, with: String) -> AnyObject? {if let first = Mirror(reflecting: self).children.first {if first.label == with {let children = Mirror(reflecting: first.value).childrenlet index = children.startIndex.advancedBy(IntMax(pos))if let value = children[index].value as? AnyObject {return value}}}return nil}static func 詢價(水果名: String) -> Int {for 價目 in 價目表 {if let price = 價目.valueAt(0, with: 水果名) as? Int {return price}}return 0}}水果.詢價("火龍果")
2016年7月1日 星期五
swift強化版的enum
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言