这是我的OptionSetType:
struct WeekdaySet: OptionSetType { let rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static let Sunday = WeekdaySet(rawValue: 1 << 0) static let Monday = WeekdaySet(rawValue: 1 << 1) static let Tuesday = WeekdaySet(rawValue: 1 << 2) static let Wednesday = WeekdaySet(rawValue: 1 << 3) static let Thursday = WeekdaySet(rawValue: 1 << 4) static let FrIDay = WeekdaySet(rawValue: 1 << 5) static let Saturday = WeekdaySet(rawValue: 1 << 6)}
我想要这样的东西:
let weekdays: WeekdaySet = [.Monday,.Tuesday]for weekday in weekdays { // Do something with weekday}在Swift 3中,标准库中没有方法
枚举一个OptionSetType(Swift 2)的元素。
OptionSet(Swift 3)。
这是一个简单地检查每一位的可能的实现
的基本原始值,并且对于设置的每个位,
返回相应的元素。
“溢出乘法”& * 2用作左移,因为<仅针对具体的整数类型定义,但不适用于IntegerType协议。 Swift 2.2:
public extension OptionSetType where RawValue : IntegerType { func elements() -> AnySequence<Self> { var remainingBits = self.rawValue var bitMask: RawValue = 1 return AnySequence { return AnyGenerator { while remainingBits != 0 { defer { bitMask = bitMask &* 2 } if remainingBits & bitMask != 0 { remainingBits = remainingBits & ~bitMask return Self(rawValue: bitMask) } } return nil } } }}
使用示例
let weekdays: WeekdaySet = [.Monday,.Tuesday]for weekday in weekdays.elements() { print(weekday)}// Output:// WeekdaySet(rawValue: 2)// WeekdaySet(rawValue: 4)
Swift 3:
public extension OptionSet where RawValue : Integer { func elements() -> AnySequence<Self> { var remainingBits = rawValue var bitMask: RawValue = 1 return AnySequence { return AnyIterator { while remainingBits != 0 { defer { bitMask = bitMask &* 2 } if remainingBits & bitMask != 0 { remainingBits = remainingBits & ~bitMask return Self(rawValue: bitMask) } } return nil } } }}总结
以上是内存溢出为你收集整理的您如何枚举Swift中的OptionSetType?全部内容,希望文章能够帮你解决您如何枚举Swift中的OptionSetType?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)