繁体   English   中英

是否可以在 SwiftUI/Swift 中改变 class function 内部的数组?

[英]Is it possible to mutate an array inside of a class function in SwiftUI/Swift?

如果我在 class 中声明了一个数组,是否可以从该类的一个函数中改变该数组? 我希望有一些等效的“变异”关键字可用于类:

class className: ObservableObject {
    @Published var arrayName: [arrayType] = []

    func mutateArray(address: String) {
        self.arrayName = []
        let geocoder = Geocoder(accessToken: 'accessTokenHere')
        geocoder.geocode(ForwardGeocodeOptions(query: address) { (placemarks, attribution, error) in 
        guard let placemarks = placemarks
        else {
            return
        }
        self.arrayName = [value1, value2, value3]
        //This only updates the array inside this closure/context. Is there any way to have the update persist after the function has ended?
    }
}

类不需要mutating的等价物,因为它是引用类型,不像结构是值类型,这就是它需要mutating函数的原因。 在你的 Xcode-playground 上试试这个代码:

import Foundation

class className {
    var arrayName: [String] = []

    func mutateArray() {
        arrayName = ["value1", "value2", "value3"]
    }
}
let object = className()
print(object.arrayName)
object.mutateArray()
print(object.arrayName)

应在主队列上更新已发布的属性,因此请执行以下操作

class ClassName: ObservableObject {
    @Published var arrayName: [arrayType] = []

    func mutateArray(address: String) {
        self.arrayName = []
        let geocoder = Geocoder(accessToken: 'accessTokenHere')
        geocoder.geocode(ForwardGeocodeOptions(query: address) { [weak self] (placemarks, attribution, error) in
            guard let placemarks = placemarks
                else {
                    return
            }
            DispatchQueue.main.async {     // << here !!
                self?.arrayName = [value1, value2, value3] // << weak for safety
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM