llanfair
llanfair

Reputation: 1885

Swift 3 - Making class iterable

Consider my two classes:

// Person.swift
class Person {
    var parents: Parents?
    // ...
}

// Parents.swift. Only a collection of parents with some helper methods.
class Parents {
    var parents = [Person]()
    // ...
}

How could I make Parents iterate in a for loop using the iterators of parents. This is not a real world app. I'm just curious. Just would like to use for parent in myParents instead of for parent in myParents.parents.

Upvotes: 4

Views: 2778

Answers (1)

user887210
user887210

Reputation:

The way to do this is to have your Parents class conform to the Sequence Protocol, implement a makeIterator method, and then pass the result through from calling makeIterator on the contained Array<Person>

  // Person.swift
  class Person {
    var parents: Parents?
    // ...
  }

  // Parents.swift. Only a collection of parents with some helper methods.
  class Parents{
    var parents = [Person]()
    // ...
  }

  // conform to Sequence Protocol
  extension Parents: Sequence {
    func makeIterator() -> Array<Person>.Iterator {
      return parents.makeIterator()
    }
  }

  let myself = Person()
  if let myParents = myself.parents {
    for person in myParents {

    }
  }

Upvotes: 7

Related Questions