【问题标题】:How can I auto-sort an array in Swift by property type?如何在 Swift 中按属性类型对数组进行自动排序?
【发布时间】:2015-02-27 03:41:46
【问题描述】:

我正在尝试在结构中创建一个变异函数,该函数将按其 String 属性对数组进行排序。这样,每当将一个项目添加到数组中时,它都会按字母顺序对其自身进行排序。我意识到我现在所拥有的试图在自己的数组的 didSet 方法中对数组进行更改,但我不确定现在该去哪里。目前我收到错误“线程 1:EXC_BAD_ACCESS (code=2, address=...)”。在尝试实现 sort 方法之前,所有其他代码都运行良好。

import Foundation

struct QuoteLibrary {
    var title : String
    var arrayOfSectionTitles: [String]
    var arrayOfSections : [Section] = [] {
        didSet {
            self.configureSections()
        }
    }

    mutating func configureSections() {
        // Sort alphabetically
        arrayOfSections.sort({ $0.title > $1.title })

        let numberOfSections = arrayOfSections.count - 1

        // Update the arrayOfSectionTitles whenever arrayOfSections is set
        var titleArray: [String] = []
        for k in 0...numberOfSections {
            titleArray.append(arrayOfSections[k].title)
        }
        arrayOfSectionTitles = titleArray

        // If a section has no quotes in it, it is removed
        for j in 0...numberOfSections {
            if arrayOfSections[j].arrayOfQuotes.count == 0 {
                arrayOfSections.removeAtIndex(j)
                return
            }
        }

    }
}

struct Section {
    var title : String, arrayOfQuotes:[Quote]
}

struct Quote {
    var section : String, text : String
}

enum QuoteStatus: Int {
    case Unchanged = 0
    case Changed = 1
    case Deleted = 2
    case Added = 3
}

【问题讨论】:

    标签: arrays sorting swift properties


    【解决方案1】:

    你有一个递归问题。每次触摸arrayOfSections,它都会调用configureSections包括 configureSectionsarrayOfSections 所做的更改,例如排序或删除空白部分。您可能会通过删除空白部分来摆脱它(因为在删除之后,后续调用不会删除任何内容,因此不会更改数组并重新调用函数),但是对它进行排序会将事情推过去边缘。

    使用私有数组可能会更好,然后使用提供访问它的计算属性,如下所示:

    struct QuoteLibrary {
        private var _arrayOfSections: [Section] = []
    
        var title: String
        var arrayOfSectionTitles: [String] = []
    
        var arrayOfSections: [Section] {
            get { return _arrayOfSections }
            set(newArray) {
                _arrayOfSections = newArray.filter { !$0.arrayOfQuotes.isEmpty }
                _arrayOfSections.sort { $0.title > $1.title }
                arrayOfSectionTitles = _arrayOfSections.map { $0.title }
            }
        }
    
        init(title: String) { self.title = title }
    }
    

    此外,您肯定希望研究 Swift 的映射、数组过滤等功能,以替代您的 for 循环。尤其是你的 remove 循环——在你迭代数组时从数组中删除元素真的很棘手,filter 更不容易出错。

    【讨论】:

    • 效果很好!谢谢你的帮助。我将不得不更多地研究映射和过滤。仍在学习绳索...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多