Creating Your Own Set Types - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.11 Creating Your Own Set Types

Problem

You want to create a type in Swift that can allow all operators that normal sets allow, such as the contain function.

Solution

Conform to the OptionSetType protocol. As a bonus, you can also conform to the CustomDebugStringConvertible protocol, as I will do in this recipe, in order to set custom debug descriptions that the print function can use during debugging of your sets.

Discussion

Let’s say that I have a structure that keeps track of iPhone models. I want to be able to create a set of this structure’s values so that I can say that I have an iPhone 6, iPhone 6+, and iPhone 5s (fancy me!). Here is the way I would do that:

struct IphoneModels : OptionSetType, CustomDebugStringConvertible{

let rawValue: Int

init(rawValue: Int){

self.rawValue = rawValue

}

static let Six = IphoneModels(rawValue: 0)

static let SixPlus = IphoneModels(rawValue: 1)

static let Five = IphoneModels(rawValue: 2)

static let FiveS = IphoneModels(rawValue: 3)

var debugDescription: String{

switch self{

case IphoneModels.Six:

return "iPhone 6"

case IphoneModels.SixPlus:

return "iPhone 6+"

case IphoneModels.Five:

return "iPhone 5"

case IphoneModels.FiveS:

return "iPhone 5s"

default:

return "Unknown iPhone"

}

}

}

And then I can use it like so:

func example1(){

let myIphones: [IphoneModels] = [.Six, .SixPlus]

if myIphones.contains(.FiveS){

print("You own an iPhone 5s")

} else {

print("You don't seem to have an iPhone 5s but you have these:")

for i in myIphones{

print(i)

}

}

}

Note how I could create a set of my new type and then use the contains function on it just as I would on a normal set. Use your imagination--this is some really cool stuff.

See Also