Jan Klaas
Jan Klaas

Reputation: 371

Return different Types with getter method on a variable in Swift 2

I've making a Hangman game which has two modes: normal and evul. Normal and evul are both subclasses of mode. The class mode saves up things like: good guessed letters, wrong guessed letters and mode has a guess function.

class Mode Normal: Mode Evul: Mode

Now I wanna make my code as simple as possible, so I thought that before start the game and when the view get's loaded I will initiate either the evul subclass or the normal subclass. I got a local variable called which returns return or false based on the fact if evulmode is enabled or not. So when it's not the getter function will initiate the normal subclass. So like this I dont need any if statements anymore and makes my gamecode alot simpler.

Problem: since the normal subclass is of another type than evul subclass it wont work. This is the error I get:cannot convert returntype x to type x.

This is the code I have:

    var Game: Normal {
    get {
        if evulMode == false {
            return(Normal())
        } else {
            return(Evul())
        }
    }
}

A Solution or any f

Feedback on how to do it better is appriciated.

Upvotes: 1

Views: 291

Answers (1)

R Menke
R Menke

Reputation: 8391

I would make Mode rawRepresentable and then create an enum to represent all game mode options. Then you can create a variable with the enum as type.

To make your code work, give the variable the superclass type. Then use a downcast.

class Mode {

}

class Normal : Mode {
    let someAttr : Int = 10
}

class Evul : Mode {
    let someOtherAttr : String = "ABC"
}

var evulMode : Bool = false


var game: Mode {
    get {
        if evulMode == false {
            return(Normal())
        } else {
            return(Evul())
        }
    }
}

After downcasting you will have access to all properties and methods specific to the subclass.

if let normalGame = game as? Normal {
    print(normalGame.someAttr)
}

if let evulGame = game as? Evul {
    print(evulGame.someOtherAttr)
}

Mode can also be a protocol. You just need something both Normal and Evul conform too or inherit from. Protocols have the advantage that you can conform to multiple protocols while you can only inherit from one superclass.

protocol Mode {

}

Upvotes: 2

Related Questions