微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。