簡體   English   中英

如何對數組類型的變量使用getter和setter來通過索引而不是整個數組本身訪問數組的項

[英]How do I use getters and setters for a variable of type array to access items of the array by index instead of the entire array itself

class SomeClass {
     var dates: [Date] {
          get {
               return ckRecord.object(forKey: "dates") as! [Date]
          }
          set(newDates) {
               ckRecord.setObject(newDates as! CKRecordValue, "dates")
          }
     }
}     

在之前的代碼中,如何在每次從數組中獲取值之一或在數組中設置值之一時,如何在get和set閉包中編寫代碼以保存到CloudKit並從CloudKit檢索數據。不會檢索整個數組或設置整個數組,只是給定索引處的值之一,如以下代碼所示:

var obj = SomeClass()
obj.dates[0] = Date()

我使用CloudKit沒問題。 我在弄清楚如何安排get和set閉包的代碼時遇到問題,這樣我才能通過索引從CloudKit記錄正確訪問數組。 我正在嘗試將CloudKit記錄包裝在SomeClass類中。

任何幫助將不勝感激。

我相信,您無法通過實現屬性的get/set來做到這一點。 但是您至少可以通過兩種方式來做到這一點:

1)提取函數中的getter / setter邏輯:

func getDate(_ index: Int) -> Date?
func set(date: Date, index: Int)

這可以正常工作,但是看起來很丑。

2)更快捷的方法是使用subscript 在這種情況下,您將創建一個包含私有dates類,並且該類允許您使用下標訪問具體日期。 簡單的例子:

class Dates {

    private var dates: [Date] = []

    subscript(index: Int) -> Date? {
        get {
            guard dates.indices.contains(index) else { return nil }
            return dates[index]
        }
        set(newValue) {
            guard let date = newValue else { return }
            dates.insert(date, at: index)
        }
    }

}

我的建議是CKRecord的擴展, CKRecord具有通過索引和索引訂閱來插入,添加和獲取日期的功能。

要修改數組,您總是必須從記錄中獲取它,然后對其進行更改並放回去。

extension CKRecord {

    func date(at index : Int) -> Date? {
        guard let dates = self["dates"] as? [Date], index < dates.count else { return nil }
        return dates[index]
    }

    func appendDate(_ date: Date) {
        guard var dates = self["dates"] as? [Date] else { return }
        dates.append(date)
        self["dates"] = dates as CKRecordValue
    }

    func insertDate(_ date : Date, at index: Int) {
        guard var dates = self["dates"] as? [Date], index <= dates.count else { return }
        dates.insert(date, at: index)
        self["dates"] = dates as CKRecordValue
    }

    public subscript(index: Int) -> Date? {
        get {
            guard let dates = self["dates"] as? [Date], index < dates.count else { return nil }
            return dates[index]
        }
        set {
            guard let newDate = newValue,
                var dates = self["dates"] as? [Date],
                dates.indices.contains(index) else { return }
            dates[index] = newDate
            self["dates"] = dates as CKRecordValue
        }
    }
}

暫無
暫無

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

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