在Swift中,如何将字符串作为类的属性名称放在函数的参数中?

问题描述

我需要通过在函数的参数中放入属性名称来分解somme计算,例如func TotalCalorie(Liste list: [[Movie]],Macro: Int) -> Int,例如year,在这种情况下:

struct Movie {
    var title = ""
    var year = 0
    var boxOffice = 0
    var isImportant: Bool
    var isFinished: Bool
    
    init(title: String,year: Int,boxOffice: Int,isImportant: Bool,isFinished: Bool) {
        self.title = title
        self.year = year
        self.boxOffice = boxOffice
        self.isImportant = isImportant
        self.isFinished = isFinished
    }

    static let list1 = [
        Movie(title: "The Shawshank Redemption",year: 1,boxOffice: 2,isImportant: false,isFinished: false),Movie(title: "The Godfather",boxOffice: 4,Movie(title: "The Dark Knight",boxOffice: 1,isFinished: false)

        ]
    
    static let list2 = [
        Movie(title: "The Lord of the Rings: The Fellowship of the Ring",year: 2,boxOffice: 3,Movie(title: "Inception",isFinished: false)
        ]
    
    static let list2Bis = [
        Movie(title: "The Lord of the Rings: The Fellowship of the Ring",boxOffice: 6,isFinished: false)
        ]
    
    static let list3 = [list1,list2,list2Bis]
    
    static let nomsDesRepas: [String] = ["Petit Déjeuner","Collation 11h"]
}



func TotalCalorie(Liste list: [[Movie]],Macro: Int) -> Int { // It's here
var totalsection = 0
var totalcalorie = 0
    
    for xxx in 0..<list.count {
        totalsection = 0
        
        for yyy in 0..<list[xxx].count {
            
        totalsection += list[xxx][yyy].year
}
    totalcalorie += totalsection
}
    return totalcalorie
}

let calories = TotalCalorie(Liste: Movie.list3,Macro: .year)
print(calories)

我必须将year或boxOffice放在我的职能参数中。 我该怎么办?

解决方法

您可以在此处尝试使用 Mirror

在方法中使用String类型的参数,并使用它通过value获取属性的Mirror

func totalCalorie(liste list: [[Movie]],macro: String) -> Int {
    var totalsection = 0
    var totalcalorie = 0
    
    list.forEach {
        totalsection = 0
        $0.forEach({ (movie) in
            if let value = Mirror(reflecting: movie).children.first(where: { $0.label == macro })?.value as? Int {
                totalsection += value
            }
        })
        totalcalorie += totalsection
    }
    return totalcalorie
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...