xcode 当在swift中编译代码行时,它会显示错误消息[已关闭]

uajslkp6  于 2023-02-09  发布在  Swift
关注(0)|答案(1)|浏览(131)

12小时前关门了。
Improve this question

import SwiftUI

struct PokemonDetailView: View {
    @EnvironmentObject var vm: ViewModel
    let pokemon: Pokemon
    
    var body: some View {
        VStack {
            PokemonView(pokemon: pokemon)
            
            VStack(spacing: 10) {
                Text("**ID**: \(vm.pokemonDetails?.id ?? 0)")
                Text("**Weight**: \($vm.formatHW(value: vm.pokemonDetails?.weight ?? 0)) KG")
                Text("**Height**: \($vm.formatHW(value: vm.pokemonDetails?.height ?? 0)) M")
            }
            .padding()
        }
        .onAppear {
            vm.getDetails(pokemon: pokemon)
}
    }
    
}

struct PokemonDetailView_Previews: PreviewProvider {
    static var previews: some View {
        PokemonDetailView(pokemon: Pokemon.samplePokemon)
            .environmentObject(ViewModel())
    }
}

编译上面的代码行时,它会在第1、2、3行文本中显示错误消息:
无法调用非函数类型"Binding"的值'
以及
类型"EnvironmentObject.Wrapper"的值没有使用根类型"ViewModel"的键路径的动态成员"formatHW".Wrapper' has no dynamic member 'formatHW' using key path from root type 'ViewModel'

rt4zxlrg

rt4zxlrg1#

注意细节,去掉$,使用formatHw而不是formatHW

VStack(spacing: 10) {
    Text("**ID**: \(vm.pokemonDetails?.id ?? 0)")
    Text("**Weight**: \(vm.formatHw(value: vm.pokemonDetails?.weight ?? 0)) KG")
    Text("**Height**: \(vm.formatHw(value: vm.pokemonDetails?.height ?? 0)) M")
}

相关问题