[英]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.