if语句中一行的连续语句

时间:2015-12-22 08:18:57

标签: swift sorting

在if语句中解决问题......

func sortStudents(students: [Student], byNames: [String] ) -> [Student]{
        var result = [Student]()

        for name in byNames {
            if let students = students.filter{ $0.sName == name}{
                if students.count > 0{
                    result.append(students[0])
                }
            }
        }
        return result
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

理论上,它将是

if let students = students.filter({ $0.sName == name }) { ... }

但是filter无论如何都不会返回可选项,因此您根本不应该使用if let语法。

所以你可以这样做:

func sortStudents(students: [Student], byNames: [String] ) -> [Student]{
    var result = [Student]()

    for name in byNames {
        let students = students.filter { $0.sName == name }
        if students.count > 0 {
            result.append(students[0])
        }
    }
    return result
}