国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Swift優雅的實現枚舉的定義及使用

2019-11-14 18:15:42
字體:
來源:轉載
供稿:網友

1、枚舉是用來表示值的“類型”。


2、定義枚舉類型“FamilyRelationshipType”

enum FamilyRelationshipType {    case GrandFather    case GrandMother    case Father    case Mother    case Brother    case Sister    case Son    case Daughter}

3、使用枚舉,指定該成員與其他成員的關系:

struct FamilyMember {    var name: String    var relationshipType: FamilyRelationshipType        init(name: String, relationshipType: FamilyRelationshipType) {        self.name = name        self.relationshipType = relationshipType    }}let sister = FamilyMember(name: "Jacky", relationshipType: FamilyRelationshipType.Sister)let brother = FamilyMember(name: "Jack", relationshipType: FamilyRelationshipType

4、指定值定義枚舉:

enum FamilyRelationshipType: Int {    case GrandFather = 400    case GrandMother = 500    case Father = 600    case Mother = 700    case Brother = 800    case Sister = 900    case Son = 1000    case Daugther = 1100}

5、Switch中使用枚舉實例:

static func giftFor(member: FamilyMember) -> String {    switch (member.relationshipType) {    case .GrandFather:        return "Book"    case .GrandMother:        return "Sweater"    case .Father:        return "Shirt"    case .Mother:        return "Flowers"    default:        return "Choclates"    }}

6、Swift 中把每個枚舉與它的值聯合起來。

enum FamilyRelationshipType {    case GrandFather(age: Int)    case GrandMother(age: Int)    case Father(age: Int)    case Mother(age: Int)    case Husband(age: Int)    case Wife(age: Int)    case Brother(age: Int)    case Sister(age: Int)    case Son(age: Int)    case Daugther(age: Int)}

完整實例,根據家庭成員的年齡大小來決定具體的禮物:

enum FamilyRelationshipType {    case GrandFather(age: Int)    case GrandMother(age: Int)    case Father(age: Int)    case Mother(age: Int)    case Husband(age: Int)    case Wife(age: Int)    case Brother(age: Int)    case Sister(age: Int)    case Son(age: Int)    case Daugther(age: Int)        func gift() -> String {        switch(self) {        case .Brother(let age):            if age > 10 {                return "video games"            } else {                return "toys"            }        case .GrandFather:            return "Book"        case .GrandMother:            return "Sweater"        case .Father:            return "Shirt"        case .Mother:            return "Flowers"        default:            return "Choclates"        }    }}struct FamilyMember {    var name: String    var relationshipType: FamilyRelationshipType        init(name: String, relationshipType: FamilyRelationshipType) {        self.name = name        self.relationshipType = relationshipType    }}

至此完整的Swift下的枚舉定義使用完成,順便推薦一下個人ios開發小站http://www.iosask.com


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广州市| 山阴县| 马尔康县| 吉林市| 巴中市| 靖边县| 通道| 柳河县| 越西县| 枞阳县| 揭阳市| 涡阳县| 汉寿县| 防城港市| 旬阳县| 日照市| 穆棱市| 吉林市| 康马县| 双鸭山市| 云梦县| 嫩江县| 上饶市| 达日县| 芦溪县| 芒康县| 页游| 武鸣县| 花垣县| 常德市| 宕昌县| 清苑县| 大同县| 河东区| 安西县| 玉山县| 武汉市| 静宁县| 五台县| 余庆县| 莫力|