OptionSet協(xié)議

三個(gè)協(xié)議

RawRepresentable協(xié)議

public protocol RawRepresentable {
associatedtype RawValue
init?(rawValue: Self.RawValue)
varrawValue: Self.RawValue {get}
}
/// The `RawRepresentable` protocol is seen mainly in two categories of types: enumerations with raw value types and option sets.1偷仿、 For any enumeration with a string, integer, or floating-point raw type, the Swift compiler automatically adds `RawRepresentable` conformance. 
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
/// 2搪花、 Option sets all conform to `RawRepresentable` by inheritance using the `OptionSet` protocol.
// 單獨(dú)使用 RawRepresentable 的情況

struct Goods: RawRepresentable {
  // 使用非可選初始化方法實(shí)現(xiàn)協(xié)議可選的初始化方法要求
  init(rawValue: Int) {
    self = Goods()
  }
  var rawValue: Int
  typealias RawValue = Int
  init() {
    self.rawValue = 0
  }
}

SetAlgebra協(xié)議

publicprotocolSetAlgebra : Equatable, ExpressibleByArrayLiteral {
/// A type for which the conforming type provides a containment test.
/// associatedtypeElement
init()
funccontains(_member: Self.Element) -> Bool
funcunion(_other: Self) -> Self
funcintersection(_other: Self) -> Self
funcsymmetricDifference(_other: Self) -> Self
mutatingfuncinsert(_newMember: Self.Element) -> (inserted: Bool, memberAfterInsert: Self.Element)
mutatingfuncremove(_member: Self.Element) -> Self.Element?
mutatingfuncupdate(with newMember: Self.Element) -> Self.Element?
mutatingfuncformUnion(_other: Self)
mutatingfuncformIntersection(_other: Self)
mutatingfuncformSymmetricDifference(_other: Self)
    ......

OptionSet協(xié)議

publicprotocolOptionSet : RawRepresentable, SetAlgebra {
associatedtypeElement = Self
init(rawValue: Self.RawValue)
}

// OptionSet等價(jià)寫法

publicprotocolOptionSet : SetAlgebra {
associatedtypeElement = Self
init(rawValue: Self.RawValue)
  associatedtypeRawValue
//init?(rawValue: Self.RawValue) // 非可選初始化方法可涵蓋此方法
varrawValue: Self.RawValue {get}
}

OptionSet 定義類型

以結(jié)構(gòu)體類型為例令杈,MusicSets 如下:

structMusicSets: OptionSet {
//typealiasElement = Self
typealiasRawValue = Int
varrawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
  }
}

// 注意: MusicSets 對(duì) SetAlgebra協(xié)議的實(shí)現(xiàn) 默認(rèn)由OptionSet Extension咱娶,見下文“OptionSet 的 Extension分析”
// 簡(jiǎn)化版
structMusicSets: OptionSet {
varrawValue: Int
// 編譯器自動(dòng)推導(dǎo)
//  typealias RawValue = Int
init(rawValue: Int) {
self.rawValue = rawValue
  }
}

// 精簡(jiǎn)版
structMusicSets: OptionSet {
varrawValue: Int
// 編譯器自動(dòng)推導(dǎo)
//  typealias RawValue = Int
// 編譯器自動(dòng)生成(包含所有需要初始化的 成員變量, rawValue)
//  init(rawValue: Int) {
//    self.rawValue = rawValue
//  }
}

// 或者
structMusicSets: OptionSet {
//  var rawValue: Int
letrawValue: Int
}

加上類屬性,如下是一個(gè)通常的OptionSet寫法

structMusicSets: OptionSet {
//  var rawValue: Int
letrawValue: Int
  // 0001
  // 0010
  // 0100
  // 1000
  // 0111
staticletclassic = MusicSets(rawValue: 1 << 0)
staticletcountry = MusicSets(rawValue: 1 << 1)
staticletrock = MusicSets(rawValue: 1 << 2)
staticletpop = MusicSets(rawValue: 1 << 3)
staticletmix = MusicSets(rawValue: 7)
}

OptionSet 使用

OptionSet 在Swift當(dāng)中 填補(bǔ)了Enum中缺少的 bitmask 位選集合的功能

functest() {
  let sets1 = MusicSets.classic
  let sets2 = MusicSets.country
  let sets3 = MusicSets.rock
  let sets4 = MusicSets.pop
  let music = MusicSets.mix
  print("Mix contains1: ", music.contains(sets1))
  print("Mix contains2: ", music.contains(sets2))
  print("Mix contains3: ", music.contains(sets3))
  print("Mix contains4: ", music.contains(sets4))

  let music2: MusicSets = [sets1, sets2, sets3]
  print("Set contains1: ", music2.contains(sets1))
  print("Set contains2: ", music2.contains(sets2))
  print("Set contains3: ", music2.contains(sets3))
  print("Set contains4: ", music2.contains(sets4))
  print("Set rawValue: ", music2.rawValue)
  }

OptionSet 的 Extension 分析

OptionSet 的 rawValue秉颗? 可以 定義String類型嗎巨朦?

Error: Type 'MusicSets2' does not conform to protocol 'SetAlgebra'
structMusicSets2: OptionSet {
    //    var rawValue: Int
letrawValue: String
//    init?(rawValue: String) {
//        <#code#>
//    }

//    init() {
//        <#code#>
//    }

//    mutating func formUnion(_ other: __owned MusicSets) {
//        <#code#>
//    }

//    mutating func formIntersection(_ other: MusicSets) {
//        <#code#>
//    }

//    mutating func formSymmetricDifference(_ other: __owned MusicSets) {
//        <#code#>
//    }
}

rawValue 改成 String 之后,就出現(xiàn)編譯錯(cuò)誤:類型'MusicSets2' 未遵守 SetAlgebra協(xié)議赶撰,很有可能一些默認(rèn)的實(shí)現(xiàn)被磨掉了舌镶。下面從 OptionSet 的擴(kuò)展中去查找答案(optionSet 有若干個(gè)擴(kuò)展,默認(rèn)實(shí)現(xiàn)了很多功能豪娜,詳情請(qǐng)參考官網(wǎng)文檔)餐胀。

Extension: 1 通用實(shí)現(xiàn)


/// `OptionSet` requirements for which default implementations
/// are supplied.
extensionOptionSet {
@inlinablepublicfuncunion(_other: Self) -> Self
@inlinablepublicfuncintersection(_other: Self) -> Self
@inlinablepublicfuncsymmetricDifference(_other: Self) -> Self
}

Extension: 2 Where 條件實(shí)現(xiàn)

/// `OptionSet` requirements for which default implementations are
/// supplied when `Element == Self`, which is the default.
extensionOptionSetwhereSelf == Self.Element {
@inlinablepublicfunccontains(_member: Self) -> Bool
@inlinablepublicmutatingfuncinsert(_newMember: Self.Element) -> (inserted: Bool, memberAfterInsert: Self.Element)
@inlinablepublicmutatingfuncremove(_member: Self.Element) -> Self.Element?
@inlinablepublicmutatingfuncupdate(with newMember: Self.Element) -> Self.Element?
}

Extension: 3 Where 條件實(shí)現(xiàn)

extensionOptionSetwhereSelf.RawValue : FixedWidthInteger {
@inlinablepublicinit()
@inlinablepublicmutatingfuncformUnion(_other: Self)
@inlinablepublicmutatingfuncformIntersection(_other: Self)
@inlinablepublicmutatingfuncformSymmetricDifference(_other: Self)
}

補(bǔ)充:協(xié)議的關(guān)聯(lián)類型測(cè)試

protocolProtocol0 {
  // 關(guān)聯(lián)類型 沒(méi)有約束、有默認(rèn)值
associatedtypeElement0 =Self
}
protocolProtocol1 {
  // 關(guān)聯(lián)類型有約束
associatedtypeElement1: UIView
}
protocolProtocol2 {
  // 關(guān)聯(lián)類型 沒(méi)有約束瘤载、有默認(rèn)值
associatedtypeElement2 = UIView
}
protocolProtocol3 {
  // 關(guān)聯(lián)類型有約束否灾、有默認(rèn)值
associatedtypeElement3: UIView = UIButton
}
protocolProtocol04 {
  // 關(guān)聯(lián)類型有約束
associatedtypeElement041: UIView
associatedtypeElement042: UIView
}
protocolProtocol4: Protocol04 {
  // 關(guān)聯(lián)類型有約束、有默認(rèn)值
associatedtypeElement041 = UIResponder
associatedtypeElement042 = UIButton
associatedtypeElement4: UIView = UIButton
}

structMusic: Protocol0, Protocol1, Protocol2, Protocol3, Protocol4 {
  // 必須指定類型
typealiasElement1 = UIButton
  // 有默認(rèn)值鸣奔,可以不指定類型墨技,也可以改變指向
typealiasElement0 = NSObject
typealiasElement2 = NSObject
//  typealias Element3 = NSObject
typealiasElement3 = UIButton
typealiasElement4 = UIButton
  // Element041 有: UIView約束,因此 Protocol4中 對(duì) Element041 的指定(成為Music的默認(rèn)指定)不符合約束要求挎狸,需要重新指定
typealiasElement041 = UIButton
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末扣汪,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子锨匆,更是在濱河造成了極大的恐慌崭别,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件恐锣,死亡現(xiàn)場(chǎng)離奇詭異紊遵,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)侥蒙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)匀奏,“玉大人鞭衩,你說(shuō)我怎么就攤上這事。” “怎么了论衍?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵瑞佩,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我坯台,道長(zhǎng)炬丸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任蜒蕾,我火速辦了婚禮稠炬,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘咪啡。我一直安慰自己首启,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布撤摸。 她就那樣靜靜地躺著毅桃,像睡著了一般。 火紅的嫁衣襯著肌膚如雪准夷。 梳的紋絲不亂的頭發(fā)上钥飞,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音衫嵌,去河邊找鬼读宙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛渐扮,可吹牛的內(nèi)容都是我干的论悴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼墓律,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼膀估!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起耻讽,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤察纯,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后针肥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體饼记,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年慰枕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了具则。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡具帮,死狀恐怖博肋,靈堂內(nèi)的尸體忽然破棺而出低斋,到底是詐尸還是另有隱情,我是刑警寧澤匪凡,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布膊畴,位于F島的核電站,受9級(jí)特大地震影響病游,放射性物質(zhì)發(fā)生泄漏唇跨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一衬衬、第九天 我趴在偏房一處隱蔽的房頂上張望买猖。 院中可真熱鬧,春花似錦佣耐、人聲如沸政勃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)奸远。三九已至,卻和暖如春讽挟,著一層夾襖步出監(jiān)牢的瞬間懒叛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工耽梅, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留薛窥,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓眼姐,卻偏偏與公主長(zhǎng)得像诅迷,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子众旗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容