gpt4 book ai didi

swift - 在此示例中, "extension Collection where Iterator.Element: Textrepresentable"在做什么?

转载 作者:行者123 更新时间:2023-11-28 12:29:48 25 4
gpt4 key购买 nike

我得到了这个协议(protocol)和实现它的结构。

 protocol TextRepresentable {
var textualDescription: String { get }
}


struct Hamster: Textrepresentable {
var name: String
var textualDescription: String {
return "A hamster named \(name)"
}
}

下面这段代码是如何工作的?

extension Collection where Iterator.Element: TextRepresentable {
var textualDescription: String {
let itemsAsText = self.map { $0.textualDescription }
return "[" + itemsAsText.joined(separator: ", ") + "]"
}
}

扩展集合对下面这段代码做了什么?

let murrayTheHamster = Hamster(name: "Murray")
let morganTheHamster = Hamster(name: "Morgan")
let mauriceTheHamster = Hamster(name: "Maurice")
let hamsters = [murrayTheHamster, morganTheHamster, mauriceTheHamster]

print(hamsters.textualDescription)

最佳答案

这段代码

extension Collection where Iterator.Element: TextRepresentable {
var textualDescription: String {
let itemsAsText = self.map { $0.textualDescription }
return "[" + itemsAsText.joined(separator: ", ") + "]"
}
}

Collection 上创建一个扩展,只有当 Collection 中的元素 TextRepresentable 时才有效(即. 符合协议(protocol) TextRepresentable)。如果 Collection 是这种情况(Array 是一个 Collection),则扩展添加一个计算属性 textualDescription集合

在您的示例代码中,hamsters 仅包含符合 TextRepresentableHamster 类型的对象。因此,编译器知道扩展名对您的 Array hamsters 有效并且属性 textualDescription 可用。

textualDescription 的实现也相当简单。

// Defines a property named textualDescription of type String
var textualDescription: String {

// Calls textualDescription on every element of the array
// and adds the return values to a new array itemsAsText
let itemsAsText = self.map { $0.textualDescription }

// Creates a string starting with "[" followed by
// all the elements in itemsAsText, separated by ",",
// and a "]". Then, returns that String
return "[" + itemsAsText.joined(separator: ", ") + "]"
}

关于swift - 在此示例中, "extension Collection where Iterator.Element: Textrepresentable"在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42328552/

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