swift 源码学习之OptionSet

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

主要实现了三个方法

@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)

  }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,451评论 0 13
  • 久不联系的一个朋友突然给我发微信,内容大概是说她活得很失败,没有一个朋友坚定的站在她的身边,很孤独,现在找不到说话...
    余不三阅读 7,784评论 2 2
  • 我支付宝有7万多,微信有2万多, 如果我哪天突然意外死了, 这些钱会怎么处理(我的家人并不知道这笔钱)?
    _Charmy阅读 496评论 0 0
  • 窗外梧桐 旖旎风光 丝烟笼罩着的清晨,朦胧而醒素,沉浸在睡梦中的我,像偷吃了蜜,嘴角微微上扬,听得到清晨的活泼,灵...
    木時兮阅读 337评论 0 4
  • 背景:就拿今天去面试的去哪儿网来说好了 奖品:滴滴5折优惠券(因为携程与滴滴在合作) 以及人气酒店优惠券 高铁票等...
    Sakura_c776阅读 129评论 0 0