gpt4 book ai didi

swiftui - SwiftUI 中的记忆化?

转载 作者:行者123 更新时间:2023-12-04 04:15:00 28 4
gpt4 key购买 nike

我来自 React,在那里我使用 useMemo 来确保某些计算不会过于频繁地执行。我如何在 SwiftUI 中做类似的事情?

考虑这个例子:

struct MyView: View {
var records: [Record]

var body: some View {
Text("expensive summary: \(self.expensiveSummary)")
}

var expensiveSummary: String {
// based on records, return string
// containing a summary of records

return ""
}
}

有什么方法可以确保我的 expensiveSummary 仅在我的记录数组更改时被调用?

最佳答案

我认为我们可以创建一个包装器 View 作为 Equatable。(也许,我们可以使用 EquatableView.equatable() 修饰符吗?)

struct UseMemo<KeyType: Equatable, ViewType: View>: View, Equatable {
let key: KeyType
let content: (KeyType) -> ViewType

var body: some View {
content(key)
}

static func ==(lhs: UseMemo, rhs: UseMemo) -> Bool {
return lhs.key == rhs.key
}
}
struct MyView: View {
@State var records: [Int] = (Array<Int>)(1...10000)
@State var other = false

var body: some View {
VStack {
Button("Update other", action: { self.other.toggle() })
Text("Other: \(String(other))") // This will be called everytime

Button("Update records", action: { self.records.append(1) })

UseMemo(key: records) { keys in
// This is not called even if updated "other"
// This is called when updates "records"
Text("expensive summary: \(expensiveSummary)")
}

// This will be called everytime
Text("expensive summary: \(expensiveSummary)")
}
}

var expensiveSummary: String {
String(records.randomElement()!)
}
}

以下内容对我有帮助。

关于swiftui - SwiftUI 中的记忆化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893458/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com