簡體   English   中英

如何在Swift中按屬性類型對數組進行自動排序?

[英]How can I auto-sort an array in Swift by property type?

我正在嘗試在結構中創建一個變異函數,該結構將按其String屬性對數組進行排序。 這樣,每當將一個項目添加到數組中時,它將按字母順序對其進行排序。 我意識到我現在所擁有的試圖在自己的數組的didSet方法中對數組進行更改,但是我不確定現在在哪里使用它。 當前,我收到錯誤“線程1:EXC_BAD_ACCESS(代碼= 2,地址= ...)”。 在嘗試實現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
}

您有遞歸問題。 每次觸摸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出錯率要低得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM