Swift implements bitmask Option (Enum)

Source: Internet
Author: User
Tags bitmask



The implementation of Ns_option in OBJC in Swift is achieved not through enum, but through conform Rawoptionsettype protocol's struct.



The code is as follows:


struct Test : RawOptionSetType {
    typealias RawValue = UInt
    private var value: UInt = 0
    init(_ value: UInt) { self.value = value }
    init(rawValue value: UInt) { self.value = value }
    init(nilLiteral: ()) { self.value = 0 }
    static var allZeros: Test { return self(0) }
    static func fromMask(raw: UInt) -> Test { return self(raw) }
    var rawValue: UInt { return self.value }
     
    static var None: Test { return self(0) }
    static var T1: Test { return Test(1 << 0) }
    static var T2: Test { return Test(1 << 1) }
}


Viewing Rawoptionsettype will find that there are equable and Bitwiseoperationstype not implemented. This is actually the SWIFT standard library through the generic implementation can refer to this article on the Nshipster



Although Apple's approach to implementing these protocols with generic global functions reduces boilerplate code (boilerplate), there are many boilerplate in this struct. Here is a swift option generator






Swift implements bitmask Option (Enum)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.