Reputation: 131
I'm new to Swift and code and trying to figure out how to randomly select an object of a specific class and then extract the properties of that object.
I'm learning and messing around with Swift with the goal of creating some code that can create meal plans for based on predefined dishes.
I defined my list of dishes and some of their properties. I want to select one of them randomly and then list of their properties but the way I've gone about it doesn't seem to work. What's a better way to go about this?
class Food {
var name = ""
var servings:Int = 0
}
var Dishes = ["tloin", "bchick"]
var tloin = Food()
tloin.name = "Pork medalions"
tloin.servings = 3
var bchick = Food()
bchick.name = "Butter chicken"
bchick.servings = 2
var wow = Dishes.randomElement()
print ("\(wow.name) can serve \(wow.servings)")
When I sub wow
for tloin
it works just fine.
var wow = Dishes.randomElement()
print ("\(tloin.name) can serve \(tloin.servings)")
I wanted wow.servings
to tell me how many servings is the randomly selected dish but Xcode gives me this:
error: MyPlayground.playground:18:33: error: value of type 'String?' has no member 'servings'
print ("\(wow.name) can serve \(wow.servings)")
Upvotes: 2
Views: 85
Reputation: 187044
This line creates an array of strings, which have nothing to do with your local variables. They just happen to be the names of your local of variables, but nothing links them to that.
var Dishes = ["tloin", "bchick"]
What you want to do is to actually use those variables directly in creating your array. You do this by simply using the variable name, with no quotes.
After you have created your foods variables (so they exist when the array is made) add this:
var Dishes = [tloin, bchick]
The error: value of type 'String?' has no member 'servings'
means that wow
is a String
and not a Food
like you expect because you are creating an array of strings, not foods. And String
does not have a servings
peroperty, so you get this error.
Also, Array.randomElement()
returns an optional. This means Swift can't guarantee a return value. If an array has zero elements in it, asking for a random element will return nil
. So you will likely get another error:
Value of optional type 'Food?' must be unwrapped to refer to member 'name' of wrapped base type 'Food'
In this case you know for sure there are items, and you therefore know for sure that randomElement()
will return an item, so it's safe to unwrap that optional with a !
, which should fix the error.
var wow = Dishes.randomElement()!
// ^ added
Upvotes: 2