【问题标题】:Making unordered items in an array to always in same order使数组中的无序项始终保持相同的顺序
【发布时间】:2016-01-25 03:07:57
【问题描述】:

我的应用程序有一个带有 tableview 的 VC,其中包含 10 个单元格(问题)。用户选择适用于他们的任何内容,然后按"next" 按钮。然后,它转到下一个 VC 有一个表视图并初始化问题的相应部分。

例如,如果我从 10 个问题中选择“问题 1,问题 2”,那么它应该创建两个标题为“问题 1”和“问题 2”的部分。

现在我添加一个在数组中选择的问题,如下所示:

   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        result.append(allCriteria[indexPath.row])
    }

然后,当按下"next" 按钮时,它会将result 数组传递给下一个VC。根据数组“result”的传递,按顺序初始化各个部分。

问题是如果我按随机顺序按问题,它会改变部分的顺序。这是意料之中的。 有办法解决吗?

简而言之,即使用户按"Question2, Question1" 的顺序选择问题,我也希望按"Question1, Question2" 的顺序制作部分

result 数组是[Question]! 的类型,Question class 如下所示:

class Question {

    var documents: [Document] = []
    var title: String
    var description: String

    init(dict: [String:AnyObject] ) {
        // parse dict to generate a bunch of documents, add them to self.documents
        self.title = dict["Title"] as! String
        self.description = dict["Description"] as! String

        let documentsDicts = dict["Documents"] as! [Dictionary<String,AnyObject>]

        for dictionary in documentsDicts {
            let document = Document(dict: dictionary)
            self.documents.append(document)
        }
    }
}

【问题讨论】:

    标签: ios arrays swift uitableview


    【解决方案1】:

    当用户选择一个单元格时,无需将Question 添加到result 数组中,您只需将该单元格的indexPath 添加到数组中即可。当用户单击下一步时,您只需按升序对 indexPath 数组进行排序,然后基于此,您只需生成 result 数组并将其传递给下一个视图控制器,例如:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        indexPathArray.append(indexPath)
    }
    
    func next() {
        let sorted = indexPathArray.sort(<)
        let result = sorted.map {
            (var index) -> Question in 
                return allCriteria[index]
        }
        // ........
    } 
    

    【讨论】:

    • 这是 sort(
    • 这是新语法,我使用的是 xCode 7.2。由于升序是默认的排序顺序,您可以简单地使用let sorted = indexPathArray.sort() 或更简单的indexPathArray.sortInPlace() 将其排序。
    • 我不知道为什么,但如果我使用
    【解决方案2】:

    here 阅读,一个解决方案可以是按问题标题的字母顺序对数组进行排序,然后执行以下操作:

    result.sort { $0.title < $1.title }
    

    【讨论】:

      【解决方案3】:

      在 Swift 3 中

      self.resultArry.sort(by: { $0.title < $1.title })
      

      【讨论】:

        猜你喜欢
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 2011-03-05
        • 2020-04-21
        相关资源
        最近更新 更多