Custom collection in swift: is it a right way? - ios

I am learning swift. I would like to use a custom class to be loopable [able to a for...in loop] like Array. Below is the given sample code that so far, I have tried. The class in question is "GuestManager" which is holding a private collection of guests [objects of class Guest]
import Foundation
class Guest{
var guestId: String
var guestName: String
init(gId: String, name: String){
self.guestId = gId
self.guestName = name
}
}
class GuestManager: GeneratorType, SequenceType{
private var guests = [Guest]?()
private var nextIndex: Int
init(guests: [Guest]){
self.guests = guests
self.nextIndex = 0
}
func next() -> Guest? {
if self.nextIndex > (self.guests?.count)! - 1 {
self.nextIndex = 0
return nil
}
let currentGuest = self.guests![self.nextIndex]
self.nextIndex += 1
return currentGuest
}
subscript(aGuestId gID: String) -> Guest{
return (self.guests?.filter({$0.guestId == gID}).first)!
}
}
I do not want to create separate classes that are conforming to GeneratorType & SequenceType protocols. Instead I have created a single class that is conforming to both protocols.
Below are some of my questions:
I would like to know if this a correct way to have a custom collection type ?
Can we use subscript as a way to perform a search based on a property for example "subscript(aGuestId gID: String)" in the sample code above ?
It is clear from the code for next() function implementation in above sample code that is resetting the "nextIndex" when the iteration reached at the end. How one will handle the situation wherein we use a break statement inside the for...in loop as below:
for aGuest in guestManager{//guestManager an instance of GuestManager class instantiated with several guest objects
print(aGuest.guestName)
}
for aG in guestManager{
print(aG.guestId)
break
}
In the 2nd for loop the code break out after getting the first Element [Guest object in this case]. The subsequent for loop will start at index 1 in the collection and not at 0. Is there anyway to handle this break situation so that for each subsequent for looping the index is always set to 0?
Thanks
Edit: It seems the "nextIndex" reset issue can be fixed with below code [added inside GuestManager class] for generate() method implementation
func generate() -> Self {
self.nextIndex = 0
return self
}

You should not store the nextIndex inside the class. You can use a local variable in the generate method and then let that variable be captured by the closure you pass to the generator you create in that method. That’s all you need to adopt SequenceType:
class GuestManager: SequenceType{
private var guests: [Guest]
init(guests: [Guest]) {
self.guests = guests
}
func generate() -> AnyGenerator<Guest> {
var nextIndex = 0
return AnyGenerator {
guard nextIndex < self.guests.endIndex else {
return nil
}
let next = self.guests[nextIndex]
nextIndex += 1
return next
}
}
}
For subscripting, you should adopt Indexable. Actually, the easiest way to fulfill all your requirements is to pass as much of the logic for SequenceType, Indexable, and eventually (if you want to support it) CollectionType, to your array, which already has these capabilities. I would write it like this:
class GuestManager {
private var guests: [Guest]
init(guests: [Guest]){
self.guests = guests
}
}
extension GuestManager: SequenceType {
typealias Generator = IndexingGenerator<GuestManager>
func generate() -> Generator {
return IndexingGenerator(self)
}
}
extension GuestManager: Indexable {
var startIndex: Int {
return guests.startIndex
}
var endIndex: Int {
return guests.endIndex
}
subscript(position: Int) -> Guest {
return guests[position]
}
}
Some more observations:
Your guests property should not be an optional. It makes the code more complicated, with no benefits. I changed it accordingly in my code.
Your Guest class should probably be a value type (a struct). GuestManager is also a good candidate for a struct unless you require the reference semantics of a class (all collection types in the standard library are structs).

I think the subscripting approach you're trying here is kind of convoluted. Personally, I would use a function to do this for the sake of clarity.
guestManager[aGuestId: guestId]
guestManager.guestWithID(guestId)
So stylistically I would probably land on something like this
import Foundation
class Guest{
var guestId: String
var guestName: String
init(guestId: String, guestName: String){
self.guestId = guestId
self.guestName = guestName
}
}
class GuestManager: GeneratorType, SequenceType{
private var guests: [Guest]
private var nextIndex = 0
init(guests: [Guest]){
self.guests = guests
}
func next() -> Guest? {
guard guests.count < nextIndex else {
nextIndex = 0
return nil
}
let currentGuest = guests[nextIndex]
nextIndex += 1
return currentGuest
}
func guestWithID(id: String) -> Guest? {
return guests.filter{$0.guestId == id}.first ?? nil
}
}

Related

Swift: modifying data format through a button click

My goal is to use a button (that contains multiple messages) to trigger a text (making a marker such as first click will be method 1, second click will be method 2) correspondingly added at the end of the my data (after joined(separator: "~")) so that it could help me to analyze which button was clicked when I look back at the data.
Currently, I have a struct that will output the data:
struct CaptureData {
var vertices: [SIMD3<Float>] //A vector of three scalar values. It will return a list of [SIMD3<Float>(x,y,z)]
var mode: Mode = .one
mutating func nextCase() { // the data method will be changed
mode = mode.next()
}
var verticesFormatted : String { //I formatted in such a way so that it can be read more clearly without SIMD3
let v = "<" + vertices.map{ "\($0.x):\($0.y):\($0.z)" }.joined(separator: "~") + "trial: \(mode.next().rawValue)"
return "\(v)"
}
}
Based on #Joshua suggestion
enum Mode: String, CaseIterable {
case one, two, three
}
extension CaseIterable where Self: Equatable {
var allCases: AllCases { Self.allCases }
var nextCase: Self {
let index = allCases.index(after: allCases.firstIndex(of: self)!)
guard index != allCases.endIndex else { return allCases.first! }
return allCases[index]
}
#discardableResult
func next() -> Self {
return self.nextCase
}
}
And the button is alternating the messages after each click,
var x = 0
var instance = CaptureData(vertices: [SIMD3<Float>])
// Next button for changing methods
#IBAction func ChangingTapped(_ btn: UIButton) {
if(x==0){
Textfield.text = "changing to driving"
}
else if(x==1){
Textfield.text = "changing to walking"
instance.nextCase()
}
else{
Textfield.text = "changing to cycling"
instance.nextCase()
}
x += 1
}
Updates: I am able to print one of the methods , .two (method two), after separator: "~". However, at the moment I am still not be able to click button to switch the case in the data.
The main problem is the initialization of variables. I am not able to define var instance = CaptureData(vertices: [SIMD3<Float>]) because it comes with error: Cannot convert value of type '[SIMD3<Float>].Type' to expected argument type '[SIMD3<Float>]'
I am sorry if my explanation is a bit messy here. I am trying to describe the problem I have here. Let me know if there is anything missing! Thank you so much in advance.
Enums is a data type that is more like a constant but much more readable.
An example will be passing in a status to a function.
enum Status {
case success
case failure
}
func updateStatus(_ status: Status) {
statusProperty = status
}
// somewhere in your code
instance.updateStatus(.success)
versus using an Int as a value.
func updateStatus(_ status: Int) {
statusProperty = status
}
// somewhere in your code
instance.updateStatus(1) // eventually you'll forget what this and you'll declare more of a global variable acting as constant, which technically what enums are for.
Enums in swift are a bit different though, much more powerful. More info about enums here
Back to the topic.
enum Mode: String, CaseIterable {
case one, two, three
}
extension CaseIterable where Self: Equatable {
var allCases: AllCases { Self.allCases }
var nextCase: Self {
let index = allCases.index(after: allCases.firstIndex(of: self)!)
guard index != allCases.endIndex else { return allCases.first! }
return allCases[index]
}
#discardableResult
func next() -> Self { // you don't need to update self here, remember self here is one of the items in the enum, i.e. one, so assigning one = two just doesn't work.
return self.nextCase
}
}
// The data struct
struct CaptureData {
var mode: Mode = .one
// we add a mutation function here so we can update the mode
mutating func nextCase() { // the data your concern about, that can actually mutate is the mode property inside CaptureData struct.
mode = mode.next()
}
}
So lets say somewhere in the app you can use it like this you initialised an instance of CaptureData:
var instance = CaptureData() // Don't forget it should be var and not let, as we are updating its property.
instance.nextCase() // get the next case, initially it was .one
print(instance.mode) // prints two
instance.nextCase() // from .two, changes to .three
print(instance.mode) // prints three
Hope this helps.

Swift 3 - Sequence ambiguous without more context

I tried to create a custom iterator which returns wrapper abcContainer over raw data class abc
// raw data class
class abc {
var name : String = "";
init( _ value : String) {
name = value;
}
}
// with container, only "name" is to be visible
class abcContainer {
private var _abc : abc;
init( _ obj : abc) {
_abc = obj;
}
// + extra methods here
func getName() -> String {
return _abc.name
}
}
The point would be that the dictionary would return instances of abcContainer instead of just the plain raw abc class.
I wanted to use the sequence protocol to make the conversion automatic, but I was not able to transform the [String:abc] into [String:abcContainer] automatically like this:
// the iterator is implemented just iterating the inner basic dict
// but wrapping the result value as abcContainer
class abcIterator : Sequence, IteratorProtocol {
private var __source : [String:abc]?;
var index = 0
var myIterator : DictionaryIterator<String, abc>;
init(_ ctxArray: [String:abc]) {
self.__source = ctxArray
index = 0;
myIterator = (__source?.makeIterator())!
}
func next() -> abcContainer? {
let nextItem = myIterator.next();
if(nextItem != nil) {
return abcContainer((nextItem?.value)!);
}
return nil;
}
}
// this was supposed to be the wrapper over the collection
class abcCollection : Sequence {
private var __source : [String:abc]?;
init(_ list: [String:abc]) {
self.__source = list
}
func makeIterator() -> abcIterator {
return abcIterator(self.__source!);
}
}
I'm probably missing something very basic here. When I try to use the collection like this:
var dict : [String:abc] = [String:abc]();
dict["abba"] = abc("John Smith");
for (key,value) in abcCollection(dict) {
print(key, value.getName());
}
I get error: Expression type "abcCollection" is ambiguous without more context
Does anyone have idea how to make it work? What is missing? I have a feeling that this answer has the information I need...
Swift 2 to 3 Migration for Swift Sequence Protocol
The problem in your original code is that abcCollection(dict)
returned a sequence of abcContainer objects, and those cannot
be assigned to a (key, value) tuple.
You can achieve your goal with
class abcCollection : Sequence {
private var __source : [String:abc]
init(_ list: [String:abc]) {
self.__source = list
}
public func makeIterator() -> AnyIterator<(AnyObject,abcContainer)> {
let mapped = self.__source.lazy.map {
($0.key as AnyObject, abcContainer($0.value))
}
return AnyIterator(mapped.makeIterator())
}
}
Making __source non-optional makes all the (optional) unwrappings
redundant, and lazy.map { ... } returns a lazily evaluated
sequence of key/value pairs which is then type-erased.
Ok, perhaps the answer was abcIterator was not necessary, you could have defined the iterator directly just like done in the linked answer like this:
class abcCollection : Sequence {
private var __source : [String:abc]?;
init(_ list: [String:abc]) {
self.__source = list
}
public func makeIterator() -> AnyIterator<(AnyObject,abcContainer)> {
var it = self.__source?.makeIterator();
return AnyIterator {
let n = it?.next();
if n == nil { return nil }
return (n?.key as AnyObject, abcContainer((n?.value)!))
}
}
}
After that, the custom collection returned wrapped objects correctly.

Cannot convert value of type Int to expected Argument type '...'

I was trying to understand how parameters work in Swift and thus wrote a simple class as follows
class NumberIncreaser {
func numberIncrementor(var number:Int)->Int{
number += 1
return number
}
var anotherNumber = numberIncrementor(3)
}
However even after explicitly mentioning that the method 'numberIncrementor' takes an Int , Xcode asks for a numberIncreaser object(hope I am using the correct terminology , new to programming) instead. I noticed that when I remove the class the method works perfectly fine. I would like to know why this is so and how can I resolve it.
Thanks!
Your code won't compile. Consider this:
class NumberIncreaser {
static func numberIncrementor(var number:Int)->Int{
number += 1
return number
}
}
var anotherNumber = NumberIncreaser.numberIncrementor(3)
Or one another variant:
class Number {
var number: Int
init(number: Int) {
self.number = number
}
func increasedNumber() -> Int {
return number + 1
}
}
var anotherNumber = Number(number: 3).increasedNumber()
Also, don't use var in func parameter declarations:
class NumberIncreaser {
static func numberIncrementor(number: Int) -> Int {
let answer = number + 1
return answer
}
}
var anotherNumber = NumberIncreaser.numberIncrementor(3)
var parameters have been deprecated thus number is a constant which makes it immutable. You also cannot call numberIncrementor because it's an instance method.
A way out would be to make numberIncrementor a class or static method by prefixing the declaration with class or static keyword: class func numberIncrementor and you call it like so: NumberIncreaser.numberIncrementor(3).
class NumberIncreaser {
class func numberIncrementor(number: Int) -> Int {
return number + 1
}
var anotherNumber = NumberIncreaser.numberIncrementor(3)
}
Another way would be to make anotherNumber a lazy property like so:
class NumberIncreaser {
func numberIncrementor(number: Int) -> Int {
return number + 1
}
lazy var anotherNumber: Int = self.numberIncrementor(3)
}

How to refactor swift code to take protocol and struct types as method arguments

I have 2 functions that have a lot in common, and I want to re-factor my code to remove the repeated logic, however the things that are different are types, specifically a protocol, and and a struct type. The way I can think about it now is that to re-factor this I'd have 1 common method that would take one protocol type as an argument, and one struct type with the restriction that the struct type must implement the protocol 'DataDictionaryStore'. And would return an array of the protocol type passed in as argument 1
I've tried to implement this with generics, but from how I understand it, you still pass an instance as an argument when using generics, not the actual type itself.
The methods I'd like to re-factor in the code below are 'articles()', and 'authors()'
Here's the code (which can be copied to a playground Xcode 7+):
import Foundation
protocol Article {
var headline: NSString? { get }
}
protocol Author {
var firstName: NSString? { get }
}
protocol DataDictionaryStore {
init(dataDictionary: NSDictionary)
}
struct CollectionStruct {
let arrayOfModels: [NSDictionary]
//This function is identical to authors() except for return type [Article], and 'ArticleStruct'
func articles() -> [Article] {
var articlesArray = [Article]()
for articleDict in arrayOfModels {
let articleStruct = ArticleStruct(dataDictionary: articleDict)
articlesArray.append(articleStruct)
}
return articlesArray
}
func authors() -> [Author] {
var authorsArray = [Author]()
for authorDict in arrayOfModels {
let authorStruct = AuthorStruct(dataDictionary: authorDict)
authorsArray.append(authorStruct)
}
return authorsArray
}
}
struct ArticleStruct : Article, DataDictionaryStore {
var internalDataDictionary: NSDictionary
init(dataDictionary: NSDictionary) {
internalDataDictionary = dataDictionary
}
var headline: NSString? { return (internalDataDictionary["headline"] as? NSString) }
}
struct AuthorStruct : Author, DataDictionaryStore {
var internalDataDictionary: NSDictionary
init(dataDictionary: NSDictionary) {
internalDataDictionary = dataDictionary
}
var firstName: NSString? { return (internalDataDictionary["firstName"] as? NSString) }
}
var collStruct = CollectionStruct(arrayOfModels: [NSDictionary(objects: ["object1", "object2"], forKeys: ["key1", "headline"])])
print(collStruct)
var articles = collStruct.articles()
print(articles)
for article in articles {
print(article.headline)
}
If there is another way to re-factor this to remove the repeated logic, all suggestions welcome.
It's not exactly an answer to your question, but this might simplify it enough for you to be happy:
func articles() -> [Article] {
return arrayOfModels.map(ArticleStruct.init)
}
func authors() -> [Author] {
return arrayOfModels.map(AuthorStruct.init)
}
Based on PEEJWEEJ's answer, this refactor is also worth a shot. Instead of returning a single array, you can return a tuple of authors and articles. If you aren't going to be processing both the authors and articles arrays at once, this method is more expensive. But the syntax is much nicer than the previous solution using generics below.
func allObjects() -> (authors: [AuthorStruct], articles: [ArticleStruct]) {
let authors = arrayOfModels.map(AuthorStruct.init)
let articles = arrayOfModels.map(ArticleStruct.init)
return(authors, articles)
}
You would then call the method like this:
let objects = collection.allObjects()
let authors = objects.authors
let articles = objects.articles
I'm not a huge fan of the clarity here but maybe you can refactor it a bit. It seems to work at least.
func allObjectsOfType<T>(type: T.Type) -> [T] {
var objectArray = [T]()
for objectDict in arrayOfModels {
var objectStruct: T?
if type == Author.self {
objectStruct = AuthorStruct(dataDictionary: objectDict) as? T
} else if type == Article.self {
objectStruct = ArticleStruct(dataDictionary: objectDict) as? T
}
guard objectStruct != nil else {
continue
}
objectArray.append(objectStruct!)
}
return objectArray
}
You can then call it like this...
collection.allObjectsOfType(Author)
collection.allObjectsOfType(Article)

Swift: Cast generic type into same generic type but with a subclass of associated type

Consider these classes:
struct OrderedSet<T: Hashable> {}
class Exercise: Hashable {}
class StrengthExercise: Exercise {}
class CardioExercise: Exercise {}
I'd like to do the following:
var displayedExercises = OrderedSet<Exercise>() {
didSet {
self.tableView.reloadData()
}
}
var cardioExercises = OrderedSet<CardioExercise>()
var strengthExercises = OrderedSet<StrengthExercise>()
#IBAction func segmentControlChanged(segmentControl: UISegmentedControl) {
switch segmentControl.selectedSegmentIndex {
case 0: self.displayedExercises = self.strengthExercises
case 1: self.displayedExercises = self.cardioExercises
default: break
}
}
But I get this error:
Cannot assign value of type 'OrderedSet<StrengthExercise>' to type 'OrderedSet<Exercise>
I don't quite get this, since StrengthExercise is a subclass of Exercise and will have everything that OrderedSet<Exercise> expects.
The question(s)
Why is this error necessary?
How to I write something that achieves the functionality I'm going for?
Radar filed
rdar://23608799
Blog post on covariance and contravariance
https://www.mikeash.com/pyblog/friday-qa-2015-11-20-covariance-and-contravariance.html
I am afraid this is not currently possible as of Swift 2.1. Only the following conversions are supported
Built in collections types are covariant on their element type.
Conversions between function types are supported, exhibiting covariance in function result types and contravariance in function parameter types. (Cf. Xcode 7.1 Release Notes)
As Objective-C's generics support type variance, and given the progress made on function type conversions in Swift 2.1, I believe there is reason to believe type variance support will be added to Swift in the future. In the mean time, remember to file a radar, like jlieske has.
In the mean time you will have to copy the collection or use one of the builtin collection types.
Update since Swift become open source:
I believe the Complete generics section of Swift 3.0 Dev Roadmap indicates type variance will be addressed in 3.0. While type variance is not specifically called out, special cased exceptions in the standard library (which includes type variance) are.
As the OrderedSet<StrengthExercise> is of that specific type it cannot be assigned to the more general OrderedSet<Exercise>. Think about what would happen if you tried to append a Cardio exercise to that OrderedSet after assigning it.
The answer might be to modify append the contents of the strength exercises set to the exercise set rather than assign the whole typed set.
this should work
class Base {}
class A: Base {}
class B: Base {}
var arrBase: Array<Base> = []
var arrA: Array<A> = []
arrA.append(A())
var arrB: Array<B> = []
arrB.append(B())
arrBase = arrA // no error
arrBase = arrB // no error
... your trouble seems to be somewhere else in your code. can you show us your generic struct OrderedSet implementation ?? it seems like you are trying to do something like
class Base {}
class A: Base {}
let base = Base()
let a = A()
struct S<T:Base> {
var t: T
}
var s = S(t: base)
let sa = S(t: a)
//s = sa // error: cannot assign value of type 'S<A>' to type 'S<Base>'
let sb = S(t: a as Base)
s = sb
... this works
protocol P {
func whoAmI()->Void
}
class Base:P {
func whoAmI() {
print("I am Base")
}
}
class A: Base {
override func whoAmI() {
print("I am A")
}
}
let base = Base()
let a = A()
struct S<T: Base> {
var t: Base
}
var s = S(t: base)
let sa = S(t: a)
s = sa
s.t.whoAmI() // I am A
.... guys, build-in type or not
import Foundation
// Int and Double conforms to Hashable protocol
var a: Set<Int> = []
var b: Set<Double> = []
a = b // IMPOSSIBLE eventhough Set<T:Hashable> is build-in Swift type
... how to deal with OrderedSet
import Foundation
class Exercise: Hashable {
var name: String = ""
var hashValue: Int {
return name.hashValue
}
}
func ==(lhs: Exercise, rhs: Exercise) -> Bool {
return lhs.name == rhs.name
}
class StrengthExercise: Exercise {}
class CardioExercise: Exercise {}
var displayedExercises = Set<Exercise>()
let strengthExercises = Set<StrengthExercise>()
let cardioExercises = Set<CardioExercise>()
displayedExercises = strengthExercises
// OK, the question is how to implement OrderedSet<T:Hashable>
// ------------------------------------------------------------------------------------------
//
// OrderedSet.swift
// Weebly
//
// Created by James Richard on 10/22/14.
// Copyright (c) 2014 Weebly. All rights reserved.
//
// Slightly modified by user3441734 on 11/18/15
//
// original code OrderedSet is available under the MIT license
/// An ordered, unique collection of objects.
public struct OrderedSet<T: Hashable> {
private var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
private var sequencedContents = Array<UnsafeMutablePointer<T>>()
/**
Inititalizes an empty ordered set.
:return: An empty ordered set.
*/
public init() { }
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
:param: sequence The sequence to initialize the ordered set with.
:return: An initialized ordered set with the contents of sequence.
*/
public init<S: SequenceType where S.Generator.Element == T>(sequence: S) {
// FIXME: For some reason, Swift gives the error "Cannot convert the expression's type 'S' to type 'S'" with a regular for-in, so this is a hack to fix that.
var gen = sequence.generate()
while let object: T = gen.next() {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.alloc(1)
pointer.initialize(object)
sequencedContents.append(pointer)
}
}
}
/**
Replace, remove, or retrieve an object in the ordered set.
When setting an index to nil the object will be removed. If
it is not the last object in the set, all subsequent objects
will be shifted down one position.
When setting an index to another object, the existing object
at that index will be removed. If you attempt to set an index
that does not currently have an object, this is a no-op.
:param: index The index to retrieve or set.
:return: On get operations, the object at the specified index, or nil
if no object exists at that index.
*/
public subscript(index: Index) -> T {
get {
return sequencedContents[index].memory
}
set {
contents[sequencedContents[index].memory] = nil
contents[newValue] = index
sequencedContents[index].memory = newValue
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
:param: object The object to find the index for.
:return: The index of the object, or nil if the object is not in the ordered set.
*/
public func indexOfObject(object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/// The number of objects contained in the ordered set.
public var count: Int {
return contents.count
}
/// Whether the ordered set has any objects or not.
public var isEmpty: Bool {
return count == 0
}
/**
Tests if the ordered set contains an object or not.
:param: object The object to search for.
:return: true if the object exists in the ordered set, otherwise false.
*/
public func contains(object: T) -> Bool {
return contents[object] != nil
}
/**
Appends an object to the end of the ordered set.
:param: object The object to be appended.
*/
mutating public func append(object: T) {
if contents[object] != nil {
return
}
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.alloc(1)
pointer.initialize(object)
sequencedContents.append(pointer)
}
/**
Appends a sequence of objects to the end of the ordered set.
:param: objects The objects to be appended.
*/
mutating public func appendObjects<S: SequenceType where S.Generator.Element == T>(objects: S) {
var gen = objects.generate()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
:param: object The object to be removed.
*/
mutating public func remove(object: T) {
if let index = contents[object] {
contents[object] = nil
sequencedContents[index].dealloc(1)
sequencedContents.removeAtIndex(index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
}
}
/**
Removes the given objects from the ordered set.
:param: objects The objects to be removed.
*/
mutating public func removeObjects<S: SequenceType where S.Generator.Element == T>(objects: S) {
var gen = objects.generate()
while let object: T = gen.next() {
remove(object)
}
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
:param: index The index of the object to be removed.
*/
mutating public func removeObjectAtIndex(index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].memory)
}
/**
Removes all objects in the ordered set.
*/
mutating public func removeAllObjects() {
contents.removeAll()
sequencedContents.removeAll()
}
/**
Return an OrderedSet containing the results of calling
`transform(x)` on each element `x` of `self`
:param: transform A closure that is called for each element in the ordered set.
The result of the closure is appended to the new ordered set.
:result: An ordered set containing the result of `transform(x)` on each element.
*/
public func map<U: Hashable>(transform: (T) -> U) -> OrderedSet<U> {
var result = OrderedSet<U>()
for object in self {
result.append(transform(object))
}
return result
}
/// The first object in the ordered set, or nil if it is empty.
public var first: T? {
return count > 0 ? self[0] : nil
}
/// The last object in the ordered set, or nil if it is empty.
public var last: T? {
return count > 0 ? self[count - 1] : nil
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
:param: first The first object to be swapped.
:param: second The second object to be swapped.
*/
mutating public func swapObject(first: T, withObject second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].memory = second
sequencedContents[secondPosition].memory = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
:param: sequence The sequence to look for the intersection in.
:return: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersectsSequence<S: SequenceType where S.Generator.Element == T>(sequence: S) -> Bool {
var gen = sequence.generate()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
:param: sequence The sequence to check.
:return: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubsetOfSequence<S: SequenceType where S.Generator.Element == T>(sequence: S) -> Bool {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
:param: object The object to be moved
:param: index The index that the object should be moved to.
*/
mutating public func moveObject(object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position < index ? -1 : 1
let range = index < position ? index..<position : position..<index
for (object, i) in contents {
// Skip items not within the range of movement
if i < range.startIndex || i > range.endIndex || i == position {
continue
}
let originalIndex = contents[object]!
let newIndex = i + adjustment
let firstObject = sequencedContents[originalIndex].memory
let secondObject = sequencedContents[newIndex].memory
sequencedContents[originalIndex].memory = secondObject
sequencedContents[newIndex].memory = firstObject
contents[object] = newIndex
}
contents[object] = index
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
:param: index The index of the object to be moved.
:param: toIndex The index that the object should be moved to.
*/
mutating public func moveObjectAtIndex(index: Index, toIndex: Index) {
if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
:param: object The object to be inserted.
:param: atIndex The index to be inserted at.
*/
mutating public func insertObject(object: T, atIndex index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in Range(start: index, end: count-1) {
swapObject(self[i], withObject: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
:param: objects The objects to be inserted.
:param: atIndex The index to be inserted at.
*/
mutating public func insertObjects<S: SequenceType where S.Generator.Element == T>(objects: S, atIndex index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
// FIXME: For some reason, Swift gives the error "Cannot convert the expression's type 'S' to type 'S'" with a regular for-in, so this is a hack to fix that.
var gen = objects.generate()
// This loop will make use of our sequncedContents array to update the contents dictionary's
// values. During this loop there will be duplicate values in the dictionary.
while let object: T = gen.next() {
if contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.alloc(1)
element.initialize(object)
sequencedContents.insert(element, atIndex: seqIdx)
contents[object] = seqIdx
addedObjectCount++
}
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].memory] = i
}
}
}
extension OrderedSet: MutableCollectionType {
public typealias Index = Int
public typealias _Element = T
public typealias Generator = OrderedSetGenerator<T>
public func generate() -> Generator {
return OrderedSetGenerator(set: self)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count
}
}
public struct OrderedSetGenerator<T: Hashable>: GeneratorType {
public typealias Element = T
private var generator: IndexingGenerator<Array<UnsafeMutablePointer<T>>>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.generate()
}
mutating public func next() -> Element? {
return generator.next()?.memory
}
}
public func +<T: Hashable, S: SequenceType where S.Generator.Element == T> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> {
var joinedSet = lhs
joinedSet.appendObjects(rhs)
return joinedSet
}
public func +=<T: Hashable, S: SequenceType where S.Generator.Element == T> (inout lhs: OrderedSet<T>, rhs: S) {
lhs.appendObjects(rhs)
}
public func -<T: Hashable, S: SequenceType where S.Generator.Element == T> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> {
var purgedSet = lhs
purgedSet.removeObjects(rhs)
return purgedSet
}
public func -=<T: Hashable, S: SequenceType where S.Generator.Element == T> (inout lhs: OrderedSet<T>, rhs: S) {
lhs.removeObjects(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T: Hashable> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs {
if lhs.contents[object] != rhs.contents[object] {
return false
}
}
return true
}
// ------------------------------------------------------------------------------------------
// finaly what do you want
var displayedExercises1 = OrderedSet<Exercise>()
let strengthExercises1 = OrderedSet<StrengthExercise>()
let cardioExercises1 = OrderedSet<CardioExercise>()
displayedExercises = strengthExercises

Resources