Swift 3 - 集合中的结构

Swift 3 - Structs in a Collection

为什么下面的代码不起作用?我需要更改什么才能使其正常工作?

//: 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) { [=11=] + .age }
        let count = self.count as! Int
        return sum / count
    }
}

var people = [Person]()
people.append(ilse)
people.append(mark)

let averageAge = people.averageAge

我发现如果我将结构设为 Swift class 它就可以工作。它与结构是值类型有关吗?我确实在最后一行看到编译器错误。 “‘[Person]’不可转换为‘<>’”

谢谢。

extension Collection where Iterator.Element: Person

Iterator.Element限制为采用协议的类型Person 或者是 Person 子类 。两者都不可能 struct Person,在完整的编译器日志中你会发现

error: type 'Iterator.Element' constrained to non-protocol type 'Person'

你的意思可能是

extension Collection where Iterator.Element == Person 

将扩展限制为 Person 的集合。 或者,定义一个协议

protocol HasAge {
    var age: Int { get }
}

通过 Person

struct Person: CustomDebugStringConvertible, Hashable, HasAge { ... }

并定义具有年龄的元素集合的扩展名:

extension Collection where Iterator.Element: HasAge { ... }

将您的 Collection 的扩展名更改为此

extension Collection where Iterator.Element == Person {
    var averageAge: Int {
        let sum = self.reduce(0) { [=10=] + .age }
        let count = self.count as! Int
        return sum / count
    }
}