为什么下面的代码不起作用?我需要改变什么才能让它发挥作用?
//: Playground - noun: a place where people can play
import Cocoa
struct Person: CustomDebugStringConvertible, Hashable {
let name: String
let age: Int
// MARK: CustomDebugStringConvertible
var debugDescription: String {
return "\(name) is \(age) years old"
}
// MARK: Hashable
var hashValue: Int {
return name.hashValue ^ age.hashValue
}
}
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age
}
let ilse = Person(name: "Ilse", age: 33)
let mark = Person(name: "Mark", age: 38)
extension Collection where Iterator.Element: Person {
var averageAge: Int {
let sum = self.reduce(0) { $0 + $1.age }
let count = self.count as! Int
return sum / count
}
}
var people = [Person]()
people.append(ilse)
people.append(mark)
let averageAge = people.averageAge
我发现如果我将结构设为 Swift 类,它就可以工作。它与结构是值类型有关吗?我确实在最后一行看到了编译器错误。“'[Person]' 不能转换为 '<>'”
谢谢你。