![](/img/trans.png)
[英]How to get the underlying Value from a Swift KeyPath when its type is KeyPath<Root, Value!>?
[英]Swift 4 KeyPath On Objects of Different Type
我有 2 種類型, A
和B
,它們實現相同的方法並具有相同的屬性。 我已經定義了一個擴展來為A
和B
每一個獲取子屬性中的值。 我想知道是否有辦法將這 2 個擴展減少到 1 個方法。 想象一下有更多的類型,比如A
和B
所以代碼重復問題變得更糟。
更新: A
和B
與許多其他類似的東西一起生成。 最初的計划是完全避免為A
或B
編寫擴展。 我不知道這是否可行,但有人告訴我可以為此使用 KeyPaths。 屬性名稱必須不同。 這是代碼生成的副產品
struct A {
var something: Common
}
struct B {
var somethingElse: Common
}
struct Common {
var value1: String
var value2: String
}
extension A {
func valueFor(condition: Bool) -> String {
return condition ? self.something.value1 : self.something.value2
}
}
extension B {
func valueFor(condition: Bool) -> String {
return condition ? self.somethingElse.value1 : self.somethingElse.value2
}
}
我認為協議是您問題的解決方案。 它們有助於使代碼更通用。
protocol CommonContaining {
var common: Common { get set }
func valueFor(condition: Bool) -> String {
return condition ? self.common.value1 : self.common.value2
}
}
struct A {
var something: Common
}
struct B {
var somethingElse: Common
}
extension A: CommonContaining {
var common: Common {
return something
}
}
extension B: CommonContaining {
var common: Common {
return somethingElse
}
}
據我所知,如果該方法與 Common struct 相關,那么您應該在 struct 本身中實現此方法或創建對 struct 的擴展:
struct A
{
var something: Common
}
struct B
{
var somethingElse: Common
}
struct Common
{
var value1: String
var value2: String
func valueFor(condition: Bool) -> String {
return condition ? self.value1 : self.value2 }
}
var object_1 = A(something: Common(value1: "1", value2: "1"))
var object_2 = B(somethingElse: Common(value1: "1", value2: "2"))
print(object_1.something.valueFor(condition: true))
print(object_2.somethingElse.valueFor(condition: false))
祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.