英文:
How to bridge from Binding<Date?> to Binding<Date> using Extension in SwiftUI?
问题
我试图通过Binding<Date?>到Binding<Date>的扩展来进行桥接,但是我在下面的实现中遇到了问题:
每次在应用程序中使用
Binding时,它都会崩溃,并告诉我self.wrappedValue意外地找到了nil,即使在它为nil时我手动赋值为.now。
public extension Binding where Value == Date? {
var adapter: Binding<Date> {
Binding<Date>(
get: {
if self.wrappedValue == nil { self.wrappedValue = .now }
return self.wrappedValue! // CRASH
},
set: { self.wrappedValue = $0 }
)
}
}
问题:
- 在我在前一行手动设置为
.now之后,为什么self.wrappedValue会变成nil呢?
英文:
Context
I am trying to bridge from Binding<Date?> to Binding<Date> using a Extension of Binding. However, I encountered a problem with the implementation below:
> Every time the Binding gets used within the app, it crashes telling me that self.wrappedValue was unexpectedly found nil, even though I am manually assigning .now to it if it is nil.
Code
public extension Binding where Value == Date? {
var adapter: Binding<Date> {
Binding<Date>(
get: {
if self.wrappedValue == nil { self.wrappedValue = .now }
return self.wrappedValue! // CRASH
},
set: { self.wrappedValue = $0 }
)
}
}
Question
- How can
self.wrappedValuebenilafter I manually set it to.nowthe line before?
答案1
得分: 1
你不想在 get 中更新该值,因此将其更改为:
get: {
guard let value = self.wrappedValue else { return .now }
return value
}
您当前的实现应该会出现紫色警告,内容是
>在视图更新期间修改状态,这将导致未定义的行为。
这很可能是崩溃的原因。
我总是非常重视 SwiftUI 代码中出现的这些紫色警告,并直接更改有问题的代码。
英文:
You don't want to update the value during get so change it to
get: {
guard let value = self.wrappedValue else { return .now }
return value
}
Your current implementation should give you a purple warning saying
>Modifying state during view update, this will cause undefined behavior.
which is most likely the reason for the crash.
I always takes those purple warnings in my SwiftUI code very seriously and change the faulty code directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论