簡體   English   中英

SwiftUI 中的 ForEach 和 NavigationLink 問題

[英]Problem with ForEach and NavigationLink in SwiftUI

這是我遇到問題的基本代碼片段:

import SwiftUI

struct ContentView: View {
    var pets = ["Dog", "Cat", "Rabbit"]
    var body: some View {
    NavigationView {
        List {
            ForEach(pets, id: \.self) {
                NavigationLink(destination: Text($0)) {
                    Text($0)
                }
            }
        }
        .navigationBarTitle("Pets")
    }
}

我得到錯誤:

未能產生表達診斷; 請提交錯誤報告

我在這里的目的是熟悉 NavigationLink,並導航到一個新頁面,點擊該項目時只顯示文本。

任何幫助,將不勝感激。

nicksarno 已經回答了,但既然你評論你不明白,我會試一試。

$0 在沒有命名時引用當前閉包中的第一個參數。

ForEach(pets, id: \.self) {
    // $0 here means the first argument of the ForEach closure
    NavigationLink(destination: Text($0)) {
        // $0 here means the first argument of the NavigationLink closure 
        // which doesn't exist so it doesn't work
        Text($0)
    }
}

解決方案是用<name> in命名參數

ForEach(pets, id: \.self) { pet in
    // now you can use pet instead of $0
    NavigationLink(destination: Text(pet)) {
        Text(pet)
    }
}

筆記; 你得到這個奇怪錯誤的原因是因為它找到了一個不同的 NavigationLink init,它確實有一個帶參數的閉包。

它與您正在使用的速記初始化程序有關。 這些替代方案中的任何一個都可以:

ForEach(pets, id: \.self) {
     NavigationLink($0, destination: Text($0))
}

ForEach(pets, id: \.self) { pet in
     NavigationLink(destination: Text(pet)) {
          Text(pet)
     }
}

暫無
暫無

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

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