swift - if 语句中一行的连续语句

标签 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

最佳答案

理论上是这样

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
}

关于swift - if 语句中一行的连续语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34411296/

相关文章:

ios - anchor 在 Collection View 单元格布局中不起作用

通过专辑 MPMediaEntityPersistentID 的 iOS 查询有时不会带回任何歌曲

php - MySQL 中的排序/

algorithm - 对 [1, 5000] 范围内 1000 个不同整数的数组进行排序,每个元素最多访问一次

ios - 当 UIBarButtonItem 动画时 UITableView 出现故障

ios - Realm swift : All records between specific time

swift - "Cannot assign value of type ' 整数 ' to type ' 单位 ' "

C++ 对对象 vector 进行排序,出现错误 C3867 函数调用缺少参数列表?

javascript - 我想在javascript中对3维数组进行排序

c++ - 高效实现多线程排序算法的关键是什么?天真的实现不能正常工作