简体   繁体   中英

How I can build a custom Type without using any other Swift Type in Swift?

What I am trying to find out and learn is that how I could build a custom Type, for example I created this simple enum called Allowed , which has 2 cases Yes and No , and I would like to use it as real Type like Bool Type, and in the other hand I do not want just inherit Bool Type to this custom Type. How I can do that? beside this question I think this custom Type should confirm to "==" and "!=" for if statement, and Size of this type is 1 bit.

enum Allowed { case Yes, No }

use case:

let result: Allowed = Allowed.No

My Goal use case:

let result: Allowed = No
// To get == and !=, conform to Hashable
enum Allowed: Hashable {
    case yes, no // I recommend using standard naming conventions
}

let Yes = Allowed.yes  // But as global constants, capitals are probably clearer
let No = Allowed.no

let result = No // No need to include a type

As Sean notes, a two value enum will be one byte.

(I don't recommend this particular set of names, but the general approach is fine.)


To your question in the comments, if you want init() to initialized this to .no , then you would need to write that initializer:

extension Allowed {
    init() { self = .no }
}

let answer: Allowed = Allowed()

实际上,在 swift 中,您可以省略 enum 类型,因为编译器可以推断出它:

let result: Allowed = .No

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM