[英]How I can build a custom Type without using any other Swift Type in Swift?
我试图找出并学习的是如何构建自定义类型,例如我创建了一个名为Allowed 的简单枚举,它有 2 个案例Yes和No ,我想将它用作像 Bool Type 这样的真实类型,另一方面,我不想只是将 Bool 类型继承到这个自定义类型。 我怎么能做到这一点? 除了这个问题,我认为这个自定义类型应该确认为“==”和“!=”作为 if 语句,并且这种类型的大小为 1 位。
enum Allowed { case Yes, No }
用例:
let result: Allowed = Allowed.No
我的目标用例:
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
正如肖恩所指出的,两个值的枚举将是一个字节。
(我不推荐这组特定的名称,但一般方法很好。)
对于您在评论中的问题,如果您希望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.