gpt4 book ai didi

arrays - 将符合多种协议(protocol)的类型转换为单一协议(protocol)

转载 作者:可可西里 更新时间:2023-11-01 01:36:29 24 4
gpt4 key购买 nike

我很难让 Swift 理解符合两种协议(protocol)的对象数组与符合其中一种协议(protocol)的数组相同。

假设我有两个协议(protocol),Identifiable 和 Namable:

protocol Identifiable {
var identifier: Int { get }
}

protocol Namable {
var name: String { get }
}

还有两个函数将打印有关符合这些协议(protocol)的对象数组的信息:

func printIdentifiers(itemsToPrint: [Identifiable]) {
for (itemNumber, item) in itemsToPrint.enumerate() {
print("\(itemNumber): \(item.identifier)")
}
}

func printNames(itemsToPrint: [Namable]) {
for (itemNumber, item) in itemsToPrint.enumerate() {
print("\(itemNumber): \(item.name)")
}
}

然后是符合这些协议(protocol)的两个结构:

struct Friend: Identifiable, Namable {
var identifier: Int
var name: String
}

struct Dog: Identifiable, Namable {
var identifier: Int
var name: String
}

然后说我有一组符合这两个协议(protocol)的项目:

let jeff = Friend(identifier: 232314, name: "Jeff")
let fido = Dog(identifier: 45678, name: "Fido")
let identifiableAndNamableItems: [protocol<Identifiable, Namable>] = [jeff, fido]

当我将 jeff 分配给一个 Namable 变量时,Swift 没有问题:

let namableJeff: Namable = jeff //This is fine!

但是当我尝试这样做时它吓坏了:

printNames(identifiableAndNamableItems)

Cannot convert value of type [protocol<Identifiable, Namable>] to expected argument type [Namable]

知道为什么吗? Swift 凭直觉知道类型为 protocol<Identifiable, Namable> 的变量可以分配给类型为 Namable 的变量,因为任何符合两种协议(protocol)的对象必须只符合其中一种协议(protocol)。但是它不理解可以将符合两个协议(protocol)的项目数组分配给符合其中一个协议(protocol)的项目数组。

最佳答案

Swift 无法执行完整的 collection 类型转换(仅适用于某些幕后自动 Objective-C 桥接对象,或父类(super class)和子类元素的集合之间),其中 集合的元素在某种意义上是相关联的,可以将一个元素分配给另一个元素。您需要明确帮助编译器显示逐个元素的转换是有效的,例如在调用 printNames

之前使用 .map 操作
printNames(identifiableAndNamableItems.map{ $0 })
/* 0: Jeff
1: Fido */

另请注意,您无需全力以赴使用多种协议(protocol)来查看此行为;对于例如,这同样很明显。以下更小的例子

protocol Foo { }
struct Bar: Foo {}

let bar = Bar()
let foo: Foo = bar // ok

let barArr: [Bar] = [Bar(), Bar()]
let fooArr: [Foo] = barArr // cannot convert value of type '[Bar]' to specified type '[Foo]'
// let fooArr: [Foo] = barArr.map{ $0 } // OK

关于arrays - 将符合多种协议(protocol)的类型转换为单一协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901637/

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