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

In Swift, how is it possible to put a string as the name of a property of a class in a parametre of a function?

我需要分解一些计算,通过将属性名称放入函数的参数中,像这样 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", year: 1, boxOffice: 4, isImportant: false, isFinished: false),
        Movie(title: "The Dark Knight", year: 1, boxOffice: 1, isImportant: false, isFinished: false)

        ]
    
    static let list2 = [
        Movie(title: "The Lord of the Rings: The Fellowship of the Ring", year: 2, boxOffice: 3, isImportant: false, isFinished: false),
        Movie(title: "Inception", year: 2, boxOffice: 1, isImportant: false, isFinished: false)
        ]
    
    static let list2Bis = [
        Movie(title: "The Lord of the Rings: The Fellowship of the Ring", year: 2, boxOffice: 4, isImportant: false, isFinished: false),
        Movie(title: "Inception", year: 2, boxOffice: 6, isImportant: false, 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)

我必须将年份或 boxOffice 放入函数的参数中。 我该怎么做?

您可以在此处尝试使用 Mirror

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

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