@Wombat9797 (Yuto Nishime)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

SwiftUIのForEachの引数にBindingを渡した際に発生するエラーについて:「Generic parameter 'V' could not be inferred」

解決したいこと

SwiftUIをプログラミング中に発生した下記のエラーの原因が特定できません。
「Generic parameter 'V' could not be inferred」

検索しても原因を見つけることが出来なかった為、解決法をご教示いただけますと幸いです。

発生している問題・エラー

Generic parameter 'V' could not be inferred

行いたい処理

1.Playerという構造体を作成して"name"と"score"というプロパティを設定
2.1の型を@Stateプロパティの"players"配列の中で初期化
3.ForEachに2を渡して各playerから"name"と"score"プロパティにアクセス
4.両方のプロパティにアクセスできたら表示

上記の3の箇所で「Generic parameter 'V' could not be inferred」が発生してしまいます。

該当するソースコード

// ContentView.swift

struct ContentView: View {
    @State private var players: [Player] = [
        Player(name: "Elisha", score: 0),
        Player(name: "Andre", score: 0),
        Player(name: "Jasmine", score: 0)
    ]
    
    var body: some View {
        VStack {
            ForEach($players) { $player in
                TextField("Name", text: $player.name)
                
                Stepper("\(players[index].score)", value: $players[index].score)
            }
            
            Button("Add Player", systemImage: "plus") {
                players.append(Player(name: "", score: 0))
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}
// Player.swift

import Foundation

struct Player: Identifiable {
    let id = UUID()
    
    var name: String
    var score: Int
}
0 likes

1Answer

次のコードでエラーは回避できます。

-            ForEach($players) { $player in
+            ForEach(players.indices, id:\.self) { index in
-                TextField("Name", text: $player.name)
+                TextField("Name", text: $players[index].name)
                
                Stepper("\(players[index].score)", value: $players[index].score)
            }

マルチポスト?

1Like

Comments

  1. @Wombat9797

    Questioner

    @nak435
    返信遅くなりましてすみません。
    解決法のご教示ありがとうございます!
    教えて頂いたコードを試すと解決することが出来ました。

    Googleで検索しても解決法が見つからなかったのでstack overflowでも同じ質問を投稿しました!マルチポストは控えたほうが宜しいでしょうか?

Your answer might help someone💌