我如何才能在Swift中符合两个不同的协议——不一定在同一时间,而是至少其中一个



我有一个testFunction,它试图获取用于生成数组的值。由于有些类型符合CustomStringConvertible,有些则符合CustomDebugStringConvertible我为每种类型创建了两个同名函数。但我看到Xcode抱怨不明确的问题,然后我使用了不同的名称,我希望保留testFunction这样的名称,而没有testFunction1estFunction2

这是我的代码:

func testFunction1<T: CustomStringConvertible>(_ values: T...) {
    
    var array: [String] = [String]()
    values.forEach { value in
        array.append(value.description)
    }
    // other code to use array later ...
}
func testFunction2<T: CustomDebugStringConvertible>(_ values: T...) {
    
    var array: [String] = [String]()
    values.forEach { value in
        array.append(value.debugDescription)
    }
    // other code to use array later ...
 
}

问题就在这里:我可能必须接收不同类型的混合值!Swift print函数可以处理它,但我的2个函数不能,它们只能接受符合CustomStringConvertibleCustomDebugStringConvertible的类型!我正在努力解决混合类型的问题,这样我的testFunction就可以像print一样接受混合值

非常重要我希望用我正在使用的方法来解决这个问题。我不是在寻找某种涵盖CustomStringConvertibleCustomDebugStringConvertible的超级协议。

用例:

print("Hello, world!", 1, CGFloat.pi, CGSize.zero)
testFunction1("Hello, world!", 1, CGFloat.pi, CGSize.zero)
testFunction2("Hello, world!", 1, CGFloat.pi, CGSize.zero)

我认为Joakim Danielson走在正确的道路上,但我建议使用这种实现来消除重复和微妙的过滤:

func testFunction(_ values: Any...) {
    let array: [String] = values.map {
        switch $0 {
        case let v as CustomStringConvertible: return v.description
        case let v as CustomDebugStringConvertible: return v.debugDescription
        default: return "($0)"
        }
    }
    // other code to use array later ...
}

这里有一种不使用泛型的方法

func testFunction1(_ values: Any...) {
    var array: [String] = [String]()
    values.forEach { value in
        switch value.self {
        case is CustomStringConvertible:
            array.append((value as! CustomStringConvertible).description)
        case is CustomDebugStringConvertible:
            array.append((value as! CustomDebugStringConvertible).debugDescription)
        default:
            break
        }
    }
    // other code to use array later ...
}

这里的问题是您的数组。将阵列设置为var array: [T] = []

编辑:尝试删除常规约束。

func testFunction1(_ values: CustomStringConvertible...) {
    
}
func testFunction2(_ values: CustomDebugStringConvertible...) {
    
}

相关内容

最新更新