简体   繁体   English

Struct属性关闭仅在Swift中运行一次

[英]Struct property closure just run once in Swift

Have any idea to let closure just run once. 有什么想法让闭包只运行一次。

Every time I call the APIResult . 每次我调用APIResult the property which is priceSortedItems will print "123". priceSortedItems属性将显示“ 123”。 I want make it run once to reduce memory usage. 我想让它运行一次以减少内存使用量。 Thanks. 谢谢。

struct APIResult {

    var aryItem = [Item]()

    var priceSortedItems: [Item] {

        print("123")

        let sortedItems = self.aryItem.sorted(by: { (item1, item2) -> Bool in
            Double(item1.Value)! > Double(item2.Value)!
        })

        return sortedItems
    }
}

Your property is counted property with getter . 您的财产被getter计为财产。 That means every time you need to get your variable, code inside getter gets executed and you get new value from getter . 这意味着每次需要获取变量时,getter中的代码都会被执行,并且您会从getter中获取新值。

If you want to initialize your variable just once, use lazy variable which gets initialized once when is needed: 如果只想初始化一次变量,请使用lazy变量,该变量在需要时被初始化一次:

lazy var priceSortedItems: [Item] = {

    print("123")

    let sortedItems = self.aryItem.sorted(by: { (item1, item2) -> Bool in
        Double(item1.Value)! > Double(item2.Value)!
    })

    return sortedItems
}()

If you want to update priceSortedItems once aryItem changed. 如果要在aryItem更改后更新priceSortedItems You should do like this. 你应该这样

struct APIResult {

    var aryItem = [Item]() {
        didSet {
            priceSortedItems = aryItem.sorted(by: { (item1, item2) -> Bool in
                Double(item1.Value)! > Double(item2.Value)!
            })
        }
    }

    var priceSortedItems = [Item]()
}
func priceSortedItems() ->[Item] {

    print("123")

    let sortedItems = self.aryItem.sorted(by: { (item1, item2) -> Bool in
        Double(item1.Value)! > Double(item2.Value)!
    })

    return sortedItems
}

You can create it as a function. 您可以将其创建为函数。

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

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