This tutorial relies on you having completed the Simple Class tutorial. All new code should be added to this project.
Currently the LiskovPhraseMaker class allows us to set the type and subtype, but each time we overwrite the previous types. Ideally we want to store the type and subtype together as a pair, there are a number of ways of doing this, such as using dictionaries or multidimentional arrays, but the cleanest is to create a class to represent a one of the 'pairs' and store that in a collection. This tutorial uses a Array as the type of collection, but we could also use a set. (A Set may be preferable in this case, but requires some additional work).
Type
and Subtype
, set the type to string but do not give them a value. The class should appear as shown below, but Xcode will be displaying a warning indicating that TypePair has no initialisers. This is because the type and subtype variables are not declared as optionals, but if an instance of the class was created, no value would be set for them:
class TypePair {
var type :String
var subtype : String
}
init
. Add the following initialiser function to the TypePair class:
init(typeName: String, subtypeName: String){
type = typeName
subtype = subtypeName
}
private var types = Array<TypePair>()
setTypeName(typeName: subtypeName:)
method to create a TypePair class and add it to the Array as follows:
var typePair = TypePair(typeName: self.type, subtypeName: self.subtype)
types.append(typePair)
func allPairs() -> [String]{
var stringArray = [String]()
for pair in types{
var pairString = pair.subtype + ": " + pair.type
stringArray.append(pairString)
}
return stringArray
}
phraseMaker.setTypeName("Cat", subtypeName: "Feline")
phraseMaker.setTypeName("Dog", subtypeName: "Canine")
var pairArray = phraseMaker.allPairs()
for pair in pairArray{
println(pair)
}
Consider the following type and subtype pairs:
Develop the application to provide example subtypes which are further level of inheritance away, e.g. Type: Vehicle, Subtype: Hatchback
Implement the fuctionality, but use a Set, rather than an Array to store the pairs - this has the advantage that it cannot store duplicates, but also requires some additional protocols to be implemented