gpt4 book ai didi

Swift 4 使用协议(protocol)和 `Self` 伪造存在的方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:58 25 4
gpt4 key购买 nike

在 Swift 中有数百种使用协议(protocol)和 Self 来伪造存在性的解决方案,但它们大多指的是 Swift 2 和 Swift 3 可能带来的光明 future ......现在 Swift 4 已经出来了,对泛型进行了很好的补充。但我找不到任何建议如何将其放入缺失的存在问题中。

关于如何以 Swift 4 方式解决这个问题有什么想法吗?

例子:

import UIKit

protocol Bla {
func compare(other: Self)
}

extension CGFloat : Bla {
func compare(other: CGFloat) {
print("Extended CGFloat")
}
}

extension UIEdgeInsets : Bla {
func compare(other: UIEdgeInsets) {
print("Extended UIEdgeInsets")
}
}

/* Possible, but what if we want to CGFloat _and_ UIEdgeInsets inside here?
Well, that would _not_ work! */
class Possible<T: Bla> {
var array: [T]!
}

/* This is open to everything...
And therefore fails to compile, no dynamic type info at runtime I guess. */
class Fail {
var array: [Bla]!
}

// Works, but I don't need that.
let list = Possible<CGFloat>()

// I need that:
let list = Fail()
let f: CGFloat = 1.23
let edge = UIEdgeInsets()
list.array.append(f)
list.array.append(edge)

最佳答案

从根本上说,这是做不到的。如果你可以:

class Fail {
var array: [Bla]!
}

然后您可以尝试编写如下代码:

func compareAll(foo: Fail)
{
for x in foo.array
{
x.compare(other: y)
}
}

y 是什么类型?该协议(protocol)规定它必须与采用该协议(protocol)的对象的类型相同,但您直到运行时才知道 x 的类型。无法编写 y 同时为 UIEdgeInsetsCGFloat 的代码。

我认为您可以通过使 compare 通用化来消除对 Self 的依赖,从而使其工作。您的协议(protocol)将如下所示:

protocol Bla {
func compare<T: Bla>(other: T)
}

compare 的实现必须测试 other 的类型并转换为正确的类型。

extension CGFloat: Bla 
{
func compare<T: Bla>(other: T)
{
if let casted = other as? CGFloat
{
// do whatever
}
}
}

我认为这种方法比使用类型删除(参见 Daniel Hall 的回答)更好,原因如下:

  • 无需将所有内容包装在包装器对象中或 compare 的间接访问中。
  • other 是任意类型时,compare 函数可以工作,而不仅仅是相同类型的 self 如果有意义的话例如

    func compare<T: Bla>(other: T) 
    {
    if let casted = other as? CGFloat
    {
    // do whatever
    }
    else if let casted = other as? UIEdgeInsets
    {
    // Do something else
    }
    }

当然,如果只是给定协议(protocol)而您无法更改它,类型删除是您唯一的选择。

关于Swift 4 使用协议(protocol)和 `Self` 伪造存在的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074674/

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