簡體   English   中英

訪問非原始類型枚舉案例值?

[英]Accessing a non raw type enumerations case values?

所以我有一個枚舉定義如下:

enum CardPosition {
    case top(CGFloat) 
    case middle(CGFloat)
    case bottom(CGFloat) 
}

我有一個 CardPosition 類型的變量,定義為:

@State private var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100)

如何訪問 CardPosition 的值? 在這種情況下,我試圖從枚舉中訪問 UIScreen.main.bounds.height - 100 值。 我嘗試使用

self.position.rawValue 

但不幸的是,這不起作用。 任何人都知道如何訪問 position 的 CGFloat 值?

您需要在此處使用開關:

switch position {
case .top(let f):
    // use f
case .middle(let f):
    // use f
case .bottom(let f):
    // use f
}

如果你想要它作為一個表達式,你可以這樣做:

// you can assign the below to a variable or whatever
// let value =
{ () -> CGFloat in
    switch position {
    case .top(let f):
        return f
    case .middle(let f):
        return f
    case .bottom(let f):
        return f
    }
}()

但是,我認為最好的解決方案是重新設計您的類型。 似乎總會有一個CGFloat與您的枚舉的每個案例相關聯。 為什么不使用由簡單枚舉和CGFloat組成的結構?

enum RelativeCardPosition {
    case top
    case middle
    case bottom
}

struct CardPosition {
    let relativeCardPosition: RelativeCardPosition
    let offset: CGFloat
    
    static func top(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .top, offset: offset)
    }
    
    static func middle(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .middle, offset: offset)
    }
    
    static func bottom(_ offset: CGFloat) -> CardPosition {
        CardPosition(relativeCardPosition: .bottom, offset: offset)
    }
}

然后您可以通過position.offset輕松訪問該號碼。

您可以在enum CardPosition內創建一個計算屬性positionreturn每個case的關聯值,即

enum CardPosition {
    case top(CGFloat)
    case middle(CGFloat)
    case bottom(CGFloat)
    
    var position: CGFloat {
        switch self {
        case .top(let pos), .middle(let pos), .bottom(let pos):
            return pos
        }
    }
}

要獲取.bottom變量的關聯值,請使用if let case語法

var position: CardPosition = CardPosition.bottom(UIScreen.main.bounds.height - 100.0)

if case let CardPosition.bottom(positionValue) = position {
    print(positionValue)
}

這只會為您提供.bottom的值,而不是任何其他枚舉案例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM