如何使用SwiftUI中的扩展从Binding<Date?>到Binding<Date>进行桥接?

huangapple go评论53阅读模式
英文:

How to bridge from Binding<Date?> to Binding<Date> using Extension in SwiftUI?

问题

我试图通过Binding&lt;Date?&gt;Binding&lt;Date&gt;的扩展来进行桥接,但是我在下面的实现中遇到了问题:

每次在应用程序中使用Binding时,它都会崩溃,并告诉我self.wrappedValue意外地找到了nil,即使在它为nil时我手动赋值为.now


public extension Binding where Value == Date? {
    var adapter: Binding&lt;Date&gt; {
        Binding&lt;Date&gt;(
            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&lt;Date?&gt; to Binding&lt;Date&gt; 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&lt;Date&gt; {
        Binding&lt;Date&gt;(
            get: {
                if self.wrappedValue == nil { self.wrappedValue = .now }
                return self.wrappedValue! // CRASH
            },
            set: { self.wrappedValue = $0 }
        )
    }
}

Question

  • How can self.wrappedValue be nil after I manually set it to .now the 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.

huangapple
  • 本文由 发表于 2023年5月28日 21:33:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定