簡體   English   中英

SwiftUI generics 從第二個初始化程序使用

[英]SwiftUI generics used from second initialiser

我希望以與 Apple 的某些實現(例如按鈕)類似的方式構建 SwiftUI 組件。 我希望有一個 label 與該組件相關聯(這只是另一個視圖),或者能夠僅使用字符串進行構造(並且默認使用文本視圖)。

這就是我所擁有的:

struct ExampleComponent<Label> : View where Label : View {
    let label: () -> Label
    let action: () -> ()
    
    init(_ title: String, action: @escaping () -> ()) {
        self.init(label: {
            Text(title)
        }, action: action)
    }
    
    init(@ViewBuilder label: @escaping () -> Label, action: @escaping () -> ()) {
        self.label = label
        self.action = action
    }
    
    var body: some View {
        label()
    }
}

但是,由於錯誤,這無法編譯:

無法將“文本”類型的值轉換為閉包結果類型“標簽”。

怎么了?

如果您希望這是默認設置,那么您需要確保它僅適用於Label == Text的情況。 在其他情況下,您不能使用它。 我通常使用受限擴展來執行此操作:

extension ExampleComponent where Label == Text {
    init(_ title: String, action: @escaping () -> ()) {
        self.init(label: {
            Text(title)
        }, action: action)
    }
}

但是你也可以直接在init上添加約束:

init(_ title: String, action: @escaping () -> ()) where Label == Text {
    self.init(label: {
        Text(title)
    }, action: action)
}

暫無
暫無

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

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