简体   繁体   English

如何在 Swift 中不使用任何其他 Swift 类型的情况下构建自定义类型?

[英]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.我试图找出并学习的是如何构建自定义类型,例如我创建了一个名为Allowed 的简单枚举,它有 2 个案例YesNo ,我想将它用作像 Bool Type 这样的真实类型,另一方面,我不想只是将 Bool 类型继承到这个自定义类型。 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.除了这个问题,我认为这个自定义类型应该确认为“==”和“!=”作为 if 语句,并且这种类型的大小为 1 位。

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:对于您在评论中的问题,如果您希望init()将其初始化为.no ,那么您需要编写该初始化程序:

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

let answer: Allowed = Allowed()

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

let result: Allowed = .No

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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