提问者:小点点

努力将Double转换为字符串,以便将其放入对象数组中的文本SWIFTUI(SWIFT)


我正在尝试将下面的double值从我的环境对象放入一个文本,供用户查看。他是代码的一小部分,我在这里得到了一个错误,它说String类型的值必须被打开:

struct myView:View{
    @EnvironmentObject var getFood:FoodAddModel

    var unwrappedFoods:[AddedFoods]{
        getFood.foods ?? []
    }
    
    var body: some View{
        NavigationView{
        List{
        ForEach(unwrappedFoods) {obj in
            let this: String? = String(obj.totalCals)
            Text(obj.name)
            Text(this)
                }
        }
    }
    }
}

完整的文件代码:

import Foundation


import SwiftUI

struct AddedFoods:Identifiable{
    var name: String = ""
    var totalCals: Double = 0
    var totalProtein: Double = 0
    var totalCarbs: Double = 0
    var totalFat: Double = 0
    var id = UUID().uuidString
   //Your other properties
}


class FoodAddModel: ObservableObject,Identifiable {
    
    @Published var foods : [AddedFoods]?
    
    var id = UUID().uuidString

    init() {
        dummyData()
    }
    
    func dummyData() {
        var obj:[AddedFoods] = []
        obj.append(AddedFoods(name: "Pasta", totalCals: 340, totalProtein: 20, totalCarbs: 45, totalFat: 15))
        obj.append(AddedFoods(name: "Chicken", totalCals: 560, totalProtein: 20, totalCarbs: 45, totalFat: 15))
        obj.append(AddedFoods(name: "Apple", totalCals: 54, totalProtein: 20, totalCarbs: 45, totalFat: 15))
        obj.append(AddedFoods(name: "Noodles", totalCals: 231, totalProtein: 20, totalCarbs: 45, totalFat: 15))
        foods = obj
    }
}

struct myView:View{
    @EnvironmentObject var getFood:FoodAddModel

    var unwrappedFoods:[AddedFoods]{
        getFood.foods ?? []
    }
    
    var body: some View{
        NavigationView{
        List{
        ForEach(unwrappedFoods) {obj in
            let this: String? = String(obj.totalCals)
            Text(obj.name)
            Text(this)
                }
        }
    }
    }
}

如有任何帮助,我们将不胜感激:)


共1个答案

匿名用户

您可以只使用字符串插值来显示text中的Double值。您可以在这里阅读更多关于字符串插值的内容,如果您需要特定的小数位数,也可以使用String(format:)来完成这一操作,您可以在这里阅读更多内容。

像这样的东西应该管用。

struct myView:View{
    @EnvironmentObject var getFood:FoodAddModel

    var unwrappedFoods:[AddedFoods]{
        getFood.foods ?? []
    }

    var body: some View{
        NavigationView{
            List{
                ForEach(unwrappedFoods) {obj in
                    Text(obj.name)
                    Text("\(obj.totalCals)")
                    // Or if you need a fixed number of decimal places
                    Text(String(format: "%.0f", obj.totalCals))
                    Text(String(format: "%.2f", obj.totalCals))
                }
            }
        }
    }
}

注意,按照惯例,结构应该以大写字母开头,因此您的结构myview应该真正命名为myview