簡體   English   中英

檢查 object 是否為 Swift 中的泛型類型

[英]Checking if an object 'is' of a generic type in Swift

我想為 SwiftUI 的View協議添加一個擴展,它會根據實際的視圖類型改變行為:

extension View {
    func something() {
        switch self { 
            case is Text: // Do stuff.
            case is Button<AnyView>: // Do other stuff
            default: // Do other other stuff
        }
    }
}

但是,任何Button類型都不滿足is Button<AnyView>的情況。 不能不指定泛型類型,也不能指定Any 如何檢查 object is屬於泛型類型?

(顯然,我不能使用額外的、更具體的extension來覆蓋這個 function。)

好吧,不考慮這樣做的目的,如果您的按鈕設置有限,則可以使用以下內容

extension View {
    func something() -> Self {
        switch self {
            case is Text: // Do stuff.
                print("> text")
            case is Button<Text>: // Do other stuff
                    print("> text button")
            case is Button<Image>: // Do other stuff
                    print("> image button")
            default: // Do other other stuff
                print("> other")
        }
        return self
    }
}

在 Java 你想使用Button<?> ,在 Swift 這是不可能的,但你可以模擬它。

  1. 創建協議protocol AnyButton {}

  2. 現在讓所有按鈕實現這個協議: extension Button: AnyButton {}

  3. 現在您可以輕松地做您想做的事情:

     switch self { case is Text:... case is AnyButton:... }

暫無
暫無

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

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