gpt4 book ai didi

ios - Swift 的Combine 框架CombineLatest 的问题

转载 作者:行者123 更新时间:2023-12-01 16:07:13 25 4
gpt4 key购买 nike

我浏览了 WWDC 视频“Introducing Combine”,其中说每当发布者值更新时,CombineLatest 都会被调用和更新。但是我创建的代码段很奇怪。

class Mango {
var enableButton = false
@Published var userName = "admin"
@Published var password = "poweruser"
@Published var passwordAgain = "poweruser"
var validatePassword: AnyCancellable {
Publishers.CombineLatest($password, $passwordAgain).map { (password, reenterpass) -> String? in
print("Is Password Same to \(password)? :", password == reenterpass)
guard password == reenterpass else { return nil }
return password
}.eraseToAnyPublisher()
.map { (str) -> Bool in
print("In Map", str != nil)
guard str != nil else { return false }
return true
}.assign(to: \.enableButton, on: self)
}

init() {
validatePassword
}

func checkSub() {
print("1. Is password same? ->",enableButton)
password = "nopoweruser"
print("2. Is password same? ->",enableButton)
}
}


当我初始化并调用更新发布者“密码”的函数 checkSub() 时,CombineLatest 不会被调用。为什么行为异常?

输入:
let mango = Mango()<br>
mango.checkSub()

输出:
Is Password Same to poweruser? : true  
In Map true
1. Is password same? -> true
2. Is password same? -> true

最佳答案

似乎问题出在内存管理上。 validatePassword可取消是自动发布的,这意味着订阅在您创建后立即完成,因为您不保留它。使用 lazy var 使其成为属性而不是计算属性它应该可以正常工作。

lazy var validatePassword: AnyCancellable = {
Publishers.CombineLatest($password, $passwordAgain).map { (password, reenterpass) -> String? in
print("Is Password Same to \(password)? :", password == reenterpass)
guard password == reenterpass else { return nil }
return password
}.eraseToAnyPublisher()
.map { (str) -> Bool in
print("In Map", str != nil)
guard str != nil else { return false }
return true
}.assign(to: \.enableButton, on: self)
}()

lazy您保留了仅在释放对象后才释放的可取消对象。所以,这应该可以正常工作。

关于ios - Swift 的Combine 框架CombineLatest 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57306886/

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