gpt4 book ai didi

通过非可选的 Swift 协议(protocol)可选一致性

转载 作者:行者123 更新时间:2023-12-05 02:50:49 24 4
gpt4 key购买 nike

我有一个带有可选属性的协议(protocol)。

大多数符合这个协议(protocol)的类型都会有一个匹配的可选属性。但是,其中一个具有相同类型和名称的非可选属性。

protocol SomeProtocol {
var foo: Int? { get }
}

struct StructA: SomeProtocol {
let foo: Int?
}

struct StructB: SomeProtocol {
let foo: Int // Type 'StructB' does not conform to protocol 'SomeProtocol'
}

按 Xcode 的“修复 - 你想添加协议(protocol) stub 吗?”按钮添加属性的可选版本,但结构现在具有无效的重复变量名称:

struct StructB: SomeProtocol {
let foo: Int
var foo: Int? { return foo } // Invalid redeclaration of 'foo'
}

{ get } -only 的情况下,我假设这会“正常工作”,因为非可选总是满足可选的约束,类似于你如何返回一个在具有可选返回类型的函数中是非可选的。但显然情况并非如此。

这对函数也是一样的;声明 func bar() -> Int 的符合类型不满足协议(protocol)的 func bar() -> Int?

有什么办法可以解决这个问题吗?我不想重命名变量或添加中间 getter。

Swift 是否考虑过这种情况?不允许非可选变量满足可选协议(protocol)变量的合理性是什么?

最佳答案

如果协议(protocol)提供返回可选的默认实现:

protocol SomeProtocol {
var foo: Int? { get }
}

extension SomeProtocol {
var foo: Int? { return nil }
}

然后,符合协议(protocol)的类型可以提供变量/函数的覆盖非可选版本:

struct StructB: SomeProtocol {
let foo: Int
}

我在 Swift Evolution 论坛上发现了这个讨论:

At the first glance I thought there is a rule that allows us to satisfy protocol requirements with non-optional types, but this resulted in an error. Only after further investigation I noticed that a default implementation must exist in order to 'kind of override' the requirement with a non-optional version.

https://forums.swift.org/t/how-does-this-rule-work-in-regard-of-ambiguity/19448

这个 Swift 团队还讨论了允许非可选类型满足可选值协议(protocol):

Would it make any sense to allow protocol requirement satisfaction with non-optional types, like with failable init's? (Probably with some implicit optional promotion.)

是的,完全正确!除了这改变现有代码行为的部分,所以我们必须非常小心。这被认为是 [SR-522] Protocol funcs cannot have covariant returns 的一部分

在此处的 Stack Overflow 上进行了跟踪:

Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?

关于通过非可选的 Swift 协议(protocol)可选一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63459932/

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