且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift @autoclosure 在 v1.2 中破坏了枚举案例的兼容性

更新时间:2023-01-25 18:12:40

正确.这已被删除,明确地防止您提供的情况.Autoclosures 不打算以这种方式使用,Swift 团队有意取消了这样做的能力.在 Result 类型中,这是危险的,因为每次访问时都会重新评估闭包.如果关闭有副作用,这可能会产生非常令人惊讶的影响.即使它只是非平凡的,它也会产生令人惊讶的性能影响.

Correct. This has been removed, explicitly to prevent the case you provide. Autoclosures were not intended to be used this way, and the Swift team intentionally removed the ability to do so. In a Result type, this is dangerous because the closure will be re-evalated every time it is accessed. If there are side-effects in the closure, this can have quite surprising impacts. Even if it's just non-trivial, it can have surprising performance impacts.

这里正确的工具是Box.请参阅 Rob Rix 的 Result这种类型的良好实现.

The correct tool here is Box. See Rob Rix's Result for a good implementation of this type.