Bright Future Bright Future - 5 months ago 8
Swift Question

How to define a variable from an enum?

I'm trying to define a variable like this:

import UIKit

var str1 = "Apple"
var str2 = "Pear"
var str3 = "Kiwi"

enum Algorithm {

case Algorithm1
case Algorithm2
case Algorithm3

}

var chooseAlgorithm {

switch Algorithm {

case .Algorithm1:
return str1
case .Algorithm2:
return str2
case .Algorithm3:
return str3

}

}


I tried to run this code on a playground, there were so many errors, interestingly, if I try one of the fix-its prompted by Xcode, XCODE WILL CRASH.

I need to give the value of
str
to
chooseAlgorithm
, how do I achieve that?

Answer

Try this:

import UIKit

var str1 = "Apple"
var str2 = "Pear"
var str3 = "Kiwi"

enum Algorithm {
    case Algorithm1
    case Algorithm2
    case Algorithm3

    func chooseAlgorithm() -> String {
        switch self {
        case .Algorithm1:
            return str1
        case .Algorithm2:
            return str2
        case .Algorithm3:
            return str3
        }
    }
}

Algorithm.Algorithm1.chooseAlgorithm()