您如何枚举Swift中的OptionSetType?

前端之家收集整理的这篇文章主要介绍了您如何枚举Swift中的OptionSetType?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Swift中有一个自定义的OptionSetType结构。如何枚举实例的所有值?

这是我的OptionSetType:

  1. struct WeekdaySet: OptionSetType {
  2. let rawValue: UInt8
  3.  
  4. init(rawValue: UInt8) {
  5. self.rawValue = rawValue
  6. }
  7.  
  8. static let Sunday = WeekdaySet(rawValue: 1 << 0)
  9. static let Monday = WeekdaySet(rawValue: 1 << 1)
  10. static let Tuesday = WeekdaySet(rawValue: 1 << 2)
  11. static let Wednesday = WeekdaySet(rawValue: 1 << 3)
  12. static let Thursday = WeekdaySet(rawValue: 1 << 4)
  13. static let Friday = WeekdaySet(rawValue: 1 << 5)
  14. static let Saturday = WeekdaySet(rawValue: 1 << 6)
  15. }

我想要这样的东西:

  1. let weekdays: WeekdaySet = [.Monday,.Tuesday]
  2. for weekday in weekdays {
  3. // Do something with weekday
  4. }
在Swift 3中,标准库中没有方法
枚举一个OptionSetType(Swift 2)的元素。
OptionSet(Swift 3)。

这是一个简单地检查每一位的可能的实现
的基本原始值,并且对于设置的每个位,
返回相应的元素。
“溢出乘法”& * 2用作左移,因为<仅针对具体的整数类型定义,但不适用于IntegerType协议。 Swift 2.2:

  1. public extension OptionSetType where RawValue : IntegerType {
  2.  
  3. func elements() -> AnySequence<Self> {
  4. var remainingBits = self.rawValue
  5. var bitMask: RawValue = 1
  6. return AnySequence {
  7. return AnyGenerator {
  8. while remainingBits != 0 {
  9. defer { bitMask = bitMask &* 2 }
  10. if remainingBits & bitMask != 0 {
  11. remainingBits = remainingBits & ~bitMask
  12. return Self(rawValue: bitMask)
  13. }
  14. }
  15. return nil
  16. }
  17. }
  18. }
  19. }

使用示例

  1. let weekdays: WeekdaySet = [.Monday,.Tuesday]
  2. for weekday in weekdays.elements() {
  3. print(weekday)
  4. }
  5.  
  6. // Output:
  7. // WeekdaySet(rawValue: 2)
  8. // WeekdaySet(rawValue: 4)

Swift 3:

  1. public extension OptionSet where RawValue : Integer {
  2.  
  3. func elements() -> AnySequence<Self> {
  4. var remainingBits = rawValue
  5. var bitMask: RawValue = 1
  6. return AnySequence {
  7. return AnyIterator {
  8. while remainingBits != 0 {
  9. defer { bitMask = bitMask &* 2 }
  10. if remainingBits & bitMask != 0 {
  11. remainingBits = remainingBits & ~bitMask
  12. return Self(rawValue: bitMask)
  13. }
  14. }
  15. return nil
  16. }
  17. }
  18. }
  19. }

猜你在找的Swift相关文章