0

Apologies for the title gore, but I can't really think of any other way to phrase it.

I am a Swift noob and am trying to make a silly little program for practice.

Anyway, I have superclass which I plan on creating several other classes inserting the function from it but overriding the properties. I have a function that combines the properties from all the class, but I would like to be able to use the class name within the function and am completely clueless as to how to actually do this.

I have searched the documentation but did not find anything conclusive. If possible, I would also like to make the class name lowercase without actually changing the class name. Perhaps (with my vague knowledge of Python) something similar to .lower

My attempt is below:

class FoodItem {
    var ingredientOne: String = "Default ingredient."
    var ingredientTwo: String = "Also a default ingredient."
    var ingredientThree: String = "Another default ingredient."

func returnStatement() -> String {
    return "A classnamegoeshere is made from \(ingredientOne), \(ingredientTwo), and \(ingredientThree)"
    }
}
Produces
  • 31
  • 8

1 Answers1

1

Use type(of:) to get the type of self. When used in a string interpolation segment like this, it will be converted into the String representation of the type name.

return "A \(type(of: self)) is made from \(ingredientOne), \(ingredientTwo), and \(ingredientThree)"

I would go about this a bit differently though:

protocol FoodItem {
    var ingredients: (String, String, String) { get set }
}

extension Fooditem {
    func returnStatement() -> String {
        return "A \(type(of: self)) is made from \(ingredients.0), \(ingredients.1), and \(ingredients.2)"
    }
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • to make the class name lower cased you can create a string var and lower case it. Something like `let className = "\(type(of: test))".lowercased()`. And then just use it in the above return statement. – Binary Platypus May 19 '17 at 18:02