我希望能夠在這些物件的陣列中找到并更新自定義物件。挑戰在于自定義物件也可以是物件的子物件。
自定義物件如下所示:
class CustomObject: NSObject {
var id: String?
var title: String?
var childObjects: [CustomObject]?
}
我希望能夠創建一個函式,該函式使用 fx 特定 ID 覆寫自定義物件,如下所示:
var allCustomObjects: [CustomObject]?
func updateCustomObject(withId id: String, newCustomObject: CustomObject) {
var updatedAllCustomObjects = allCustomObjects
// ...
// find and update the specific custom object with the id
// ...
allCustomObjects = updatedAllCustomObjects
}
我認識到這對于 Swift 和其他語言中的多維陣列/目錄來說一定是一個非常正常的問題。請讓我知道這個問題使用什么正常做法。
uj5u.com熱心網友回復:
與大多數與樹有關的事情一樣,遞回會有所幫助。您可以添加一個額外的引數來指示CustomObject您當前正在經歷的 s 陣列,并回傳一個Bool指示是否找到 ID 的引數,以用于短路目的。
@discardableResult
func updateCustomObject(withId id: String, in objectsOrNil: inout [CustomObject]?, newCustomObject: CustomObject) -> Bool {
guard let objects = objectsOrNil else { return false }
if let index = objects.firstIndex(where: { $0.id == id }) {
// base case: if we can find the ID directly in the array passed in
objectsOrNil?[index] = newCustomObject
return true
} else {
// recursive case: we need to do the same thing for the children of
// each of the objects in the array
for obj in objects {
// if an update is successful, we can end the loop there!
if updateCustomObject(withId: id, in: &obj.childObjects, newCustomObject: newCustomObject) {
return true
}
}
return false
// technically I think you can also replace the loop with a call to "contains":
// return objects.contains(where: {
// updateCustomObject(withId: id, in: &$0.childObjects, newCustomObject: newCustomObject)
// })
// but I don't like doing that because updateCustomObject has side effects
}
}
你可以這樣稱呼它,in:引數是allCustomObjects.
updateCustomObject(withId: "...", in: &allCustomObjects, newCustomObject: ...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447173.html
下一篇:如何使用plutil獲取值?
