swift 源碼學(xué)習(xí)之OptionSet

https://github.com/apple/swift/blob/master/stdlib/public/core/OptionSet.swift

主要實(shí)現(xiàn)了三個(gè)方法

@inlinable//generic-performance

publicmutatingfuncformUnion(_other:Self) {

self=Self(rawValue:self.rawValue|other.rawValue)

? }


@inlinable//generic-performance

publicmutatingfuncformIntersection(_other:Self) {

self=Self(rawValue:self.rawValue&other.rawValue)

? }

@inlinable//generic-performance

publicmutatingfuncformSymmetricDifference(_other:Self) {

self=Self(rawValue:self.rawValue^other.rawValue)

? }

其中涉及到代理

FixedWidthInteger

RawRepresentable

SetAlgebra




A type that presents a mathematical set interface to a bit set.

///You use the `OptionSet` protocol to represent bitset types, where

///individual bits represent members of a set. Adopting this protocol in

///your custom types lets you perform set-related operations such as

///membership tests, unions, and intersections on those types. What's more,

///when implemented using specific criteria, adoption of this protocol

///requires no extra work on your part.

///When creating an option set, include a `rawValue` property in your type

///declaration. For your type to automatically receive default implementations

///for set-related operations, the `rawValue` property must be of a type that

///conforms to the `FixedWidthInteger` protocol, such as `Int` or `UInt8`.

///Next, create unique options as static properties of your custom type using

///unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual

///property's raw value so that each property can be represented by a single

///bit of the type's raw value.

///For example, consider a custom type called `ShippingOptions` that is an

///option set of the possible ways to ship a customer's purchase.

///`ShippingOptions` includes a `rawValue` property of type `Int` that stores

///the bit mask of available shipping options. The static members `nextDay`,

///`secondDay`, `priority`, and `standard` are unique, individual options.

///struct ShippingOptions: OptionSet {

///let rawValue: Int

///

///static let nextDay? ? = ShippingOptions(rawValue: 1 << 0)

///static let secondDay? = ShippingOptions(rawValue: 1 << 1)

///static let priority? = ShippingOptions(rawValue: 1 << 2)

///static let standard? = ShippingOptions(rawValue: 1 << 3)

///

///static let express: ShippingOptions = [.nextDay, .secondDay]

///static let all: ShippingOptions = [.express, .priority, .standard]

///}

///

///Declare additional preconfigured option set values as static properties

///initialized with an array literal containing other option values. In the

///example, because the `express` static property is assigned an array

///literal with the `nextDay` and `secondDay` options, it will contain those

///two elements.

/// Using an Option Set Type

///When you need to create an instance of an option set, assign one of the

///type's static members to your variable or constant. Alternatively, to

///create an option set instance with multiple members, assign an array

///literal with multiple static members of the option set. To create an empty

///instance, assign an empty array literal to your variable.


publicprotocolOptionSet:SetAlgebra,RawRepresentable{

//We can't constrain the associated Element type to be the same as

//Self, but we can do almost as well with a default and a

//constrained extension

///The element type of the option set.

///

///To inherit all the default implementations from the `OptionSet` protocol,

///the `Element` type must be `Self`, the default.

associatedtypeElement=Self


//FIXME: This initializer should just be the failable init from

//RawRepresentable. Unfortunately, current language limitations

//that prevent non-failable initializers from forwarding to

//failable ones would prevent us from generating the non-failing

//default (zero-argument) initializer.? Since OptionSet's main

//purpose is to create convenient conformances to SetAlgebra,

//we opt for a non-failable initializer.

///Creates a new option set from the given raw value.

///

///This initializer always succeeds, even if the value passed as `rawValue`

///exceeds the static properties declared as part of the option set. This

///example creates an instance of `ShippingOptions` with a raw value beyond

///the highest element, with a bit mask that effectively contains all the

///declared static members.

///

///let extraOptions = ShippingOptions(rawValue: 255)

///print(extraOptions.isStrictSuperset(of: .all))

///// Prints "true"

///

///- Parameter rawValue: The raw value of the option set to create. Each bit

///of `rawValue` potentially represents an element of the option set,

///though raw values may include bits that are not defined as distinct

///values of the `OptionSet` type.

init(rawValue:RawValue)

}

///`OptionSet` requirements for which default implementations

///are supplied.

///- Note: A type conforming to `OptionSet` can implement any of

///these initializers or methods, and those implementations will be

///used in lieu of these defaults.

extensionOptionSet{

///Returns a new option set of the elements contained in this set, in the

///given set, or in both.

///

///This example uses the `union(_:)` method to add two more shipping options

///to the default set.

///

///let defaultShipping = ShippingOptions.standard

///let memberShipping = defaultShipping.union([.secondDay, .priority])

///print(memberShipping.contains(.priority))

///// Prints "true"

///

///- Parameter other: An option set.

///- Returns: A new option set made up of the elements contained in this

///set, in `other`, or in both.

@inlinable//generic-performance

publicfuncunion(_other:Self)->Self{

varr:Self=Self(rawValue:self.rawValue)

r.formUnion(other)

returnr

? }

///Returns a new option set with only the elements contained in both this

///set and the given set.

///

///This example uses the `intersection(_:)` method to limit the available

///shipping options to what can be used with a PO Box destination.

///

///// Can only ship standard or priority to PO Boxes

///let poboxShipping: ShippingOptions = [.standard, .priority]

///let memberShipping: ShippingOptions =

///[.standard, .priority, .secondDay]

///

///let availableOptions = memberShipping.intersection(poboxShipping)

///print(availableOptions.contains(.priority))

///// Prints "true"

///print(availableOptions.contains(.secondDay))

///// Prints "false"

///- Parameter other: An option set.

///- Returns: A new option set with only the elements contained in both this

///set and `other`.

@inlinable//generic-performance

publicfuncintersection(_other:Self)->Self{

varr=Self(rawValue:self.rawValue)

r.formIntersection(other)

returnr

? }

///Returns a new option set with the elements contained in this set or in

///the given set, but not in both.

///

///- Parameter other: An option set.

///- Returns: A new option set with only the elements contained in either

///this set or `other`, but not in both.

@inlinable//generic-performance

publicfuncsymmetricDifference(_other:Self)->Self{

varr=Self(rawValue:self.rawValue)

r.formSymmetricDifference(other)

returnr

? }

}

///`OptionSet` requirements for which default implementations are

///supplied when `Element == Self`, which is the default.

///

///- Note: A type conforming to `OptionSet` can implement any of

///these initializers or methods, and those implementations will be

///used in lieu of these defaults

extensionOptionSetwhereElement==Self{

///Returns a Boolean value that indicates whether a given element is a

///member of the option set.

///

///This example uses the `contains(_:)` method to check whether next-day

///shipping is in the `availableOptions` instance.

///

///let availableOptions = ShippingOptions.express

///if availableOptions.contains(.nextDay) {

///print("Next day shipping available")

///}

///// Prints "Next day shipping available"

///

///- Parameter member: The element to look for in the option set.

///- Returns: `true` if the option set contains `member`; otherwise,

///`false`.

@inlinable//generic-performance

publicfunccontains(_member:Self)->Bool{

returnself.isSuperset(of: member)

? }

///Adds the given element to the option set if it is not already a member.

///

///In the following example, the `.secondDay` shipping option is added to

///the `freeOptions` option set if `purchasePrice` is greater than 50.0. For

///the `ShippingOptions` declaration, see the `OptionSet` protocol

///discussion.

///

///let purchasePrice = 87.55

///

///var freeOptions: ShippingOptions = [.standard, .priority]

///if purchasePrice > 50 {

///freeOptions.insert(.secondDay)

///}

///print(freeOptions.contains(.secondDay))

///// Prints "true"

///

///- Parameter newMember: The element to insert.

///- Returns: `(true, newMember)` if `newMember` was not contained in

///`self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is

///the member of the set equal to `newMember`.

@inlinable//generic-performance

@discardableResult

publicmutatingfuncinsert(

_newMember:Element

)->(inserted:Bool, memberAfterInsert:Element) {

letoldMember=self.intersection(newMember)

letshouldInsert=oldMember!=newMember

letresult=(

inserted: shouldInsert,

memberAfterInsert: shouldInsert?newMember:oldMember)

ifshouldInsert {

self.formUnion(newMember)

? ? }

returnresult

///In the next example, the `.express` element is passed to `remove(_:)`.

///Although `.express` is not a member of `options`, `.express` subsumes

///the remaining `.secondDay` element of the option set. Therefore,

///`options` is emptied and the intersection between `.express` and

///`options` is returned.

///

///let expressOption = options.remove(.express)

///print(expressOption == .express)

///// Prints "false"

///print(expressOption == .secondDay)

///// Prints "true"

///

///- Parameter member: The element of the set to remove.

///- Returns: The intersection of `[member]` and the set, if the

///intersection was nonempty; otherwise, `nil`.

///Inserts the given element into the set.

///

///If `newMember` is not contained in the set but subsumes current members

///of the set, the subsumed members are returned.

///

///var options: ShippingOptions = [.secondDay, .priority]

///let replaced = options.update(with: .express)

///print(replaced == .secondDay)

///// Prints "true"

///

///- Returns: The intersection of `[newMember]` and the set if the

///intersection was nonempty; otherwise, `nil`.

@inlinable//generic-performance

@discardableResult

publicmutatingfuncupdate(withnewMember:Element)->Element?{

letr=self.intersection(newMember)

self.formUnion(newMember)

returnr.isEmpty?nil:r

? }

}

///`OptionSet` requirements for which default implementations are

///supplied when `RawValue` conforms to `FixedWidthInteger`,

///which is the usual case.? Each distinct bit of an option set's

///`.rawValue` corresponds to a disjoint value of the `OptionSet`.

///

///- `union` is implemented as a bitwise "or" (`|`) of `rawValue`s

///- `intersection` is implemented as a bitwise "and" (`&`) of

///`rawValue`s

///- `symmetricDifference` is implemented as a bitwise "exclusive or"

///(`^`) of `rawValue`s

///

///- Note: A type conforming to `OptionSet` can implement any of

///these initializers or methods, and those implementations will be

///used in lieu of these defaults.

///`OptionSet` requirements for which default implementations are

///supplied when `RawValue` conforms to `FixedWidthInteger`,

///which is the usual case.? Each distinct bit of an option set's

///`.rawValue` corresponds to a disjoint value of the `OptionSet`.

///

///- `union` is implemented as a bitwise "or" (`|`) of `rawValue`s

///- `intersection` is implemented as a bitwise "and" (`&`) of

///`rawValue`s

///- `symmetricDifference` is implemented as a bitwise "exclusive or"

///(`^`) of `rawValue`s

///- Note: A type conforming to `OptionSet` can implement any of

///these initializers or methods, and those implementations will be

///used in lieu of these defaults.

extensionOptionSetwhereRawValue:FixedWidthInteger{

///Creates an empty option set.

///

///This initializer creates an option set with a raw value of zero.

@inlinable//generic-performance

publicinit() {

self.init(rawValue:0)

? }

///Inserts the elements of another set into this option set.

///

///This method is implemented as a `|` (bitwise OR) operation on the

///two sets' raw values.

///

///- Parameter other: An option set.

@inlinable//generic-performance

publicmutatingfuncformUnion(_other:Self) {

self=Self(rawValue:self.rawValue|other.rawValue)

? }

///Removes all elements of this option set that are not

///also present in the given set.

///

///This method is implemented as a `&` (bitwise AND) operation on the

///two sets' raw values.

///

///- Parameter other: An option set.

@inlinable//generic-performance

publicmutatingfuncformIntersection(_other:Self) {

self=Self(rawValue:self.rawValue&other.rawValue)

? }

///Replaces this set with a new set containing all elements

///contained in either this set or the given set, but not in both.

///

///This method is implemented as a `^` (bitwise XOR) operation on the two

///sets' raw values.

///

///- Parameter other: An option set.

@inlinable//generic-performance

publicmutatingfuncformSymmetricDifference(_other:Self) {

self=Self(rawValue:self.rawValue^other.rawValue)

? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末姆坚,一起剝皮案震驚了整個(gè)濱河市拱烁,隨后出現(xiàn)的幾起案子暴拄,更是在濱河造成了極大的恐慌镐作,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件呀酸,死亡現(xiàn)場(chǎng)離奇詭異凉蜂,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)性誉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門窿吩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人错览,你說我怎么就攤上這事纫雁。” “怎么了倾哺?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵轧邪,是天一觀的道長(zhǎng)刽脖。 經(jīng)常有香客問我,道長(zhǎng)忌愚,這世上最難降的妖魔是什么曲管? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮硕糊,結(jié)果婚禮上院水,老公的妹妹穿的比我還像新娘。我一直安慰自己简十,他們只是感情好檬某,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著螟蝙,像睡著了一般恢恼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上胶逢,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天厅瞎,我揣著相機(jī)與錄音,去河邊找鬼初坠。 笑死,一個(gè)胖子當(dāng)著我的面吹牛彭雾,可吹牛的內(nèi)容都是我干的碟刺。 我是一名探鬼主播,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼薯酝,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼半沽!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起吴菠,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤者填,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后做葵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體占哟,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡婆跑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年温兼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了势告。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缩擂。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡搀庶,死狀恐怖矩桂,靈堂內(nèi)的尸體忽然破棺而出晨川,到底是詐尸還是另有隱情返十,我是刑警寧澤策肝,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布肛捍,位于F島的核電站隐绵,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏拙毫。R本人自食惡果不足惜氢橙,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望恬偷。 院中可真熱鬧悍手,春花似錦、人聲如沸袍患。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽诡延。三九已至滞欠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間肆良,已是汗流浹背筛璧。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留惹恃,地道東北人夭谤。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像巫糙,于是被迫代替她去往敵國和親朗儒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

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

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,446評(píng)論 0 13
  • 久不聯(lián)系的一個(gè)朋友突然給我發(fā)微信参淹,內(nèi)容大概是說她活得很失敗醉锄,沒有一個(gè)朋友堅(jiān)定的站在她的身邊,很孤獨(dú)浙值,現(xiàn)在找不到說話...
    余不三閱讀 7,766評(píng)論 2 2
  • 我支付寶有7萬多家妆,微信有2萬多鸵荠, 如果我哪天突然意外死了, 這些錢會(huì)怎么處理(我的家人并不知道這筆錢)伤极?
    _Charmy閱讀 491評(píng)論 0 0
  • 窗外梧桐 旖旎風(fēng)光 絲煙籠罩著的清晨蛹找,朦朧而醒素姨伤,沉浸在睡夢(mèng)中的我,像偷吃了蜜庸疾,嘴角微微上揚(yáng)乍楚,聽得到清晨的活潑,靈...
    木時(shí)兮閱讀 329評(píng)論 0 4
  • 背景:就拿今天去面試的去哪兒網(wǎng)來說好了 獎(jiǎng)品:滴滴5折優(yōu)惠券(因?yàn)閿y程與滴滴在合作) 以及人氣酒店優(yōu)惠券 高鐵票等...
    Sakura_c776閱讀 126評(píng)論 0 0