Lab - Guard 2번째 문제입니다.
// Optional unwrapping 2번 해주는게 맞는지 해서요…
Imagine a screen where a user inputs a meal that they’ve eaten. If the user taps a “save” button without adding any food, you might want to prompt the user that they haven’t actually added anything.
Using the Food struct and the text fields provided below, create a function called logFood that takes no parameters and returns an optional Food object. Inside the body of the function, use a guard statement to unwrap the text property of foodTextField and caloriesTextField. In addition to unwrapping caloriesTextField, you’ll need to create and unwrap a new variable that initializes an Int from the text in caloriesTextField. If any of this fails, return nil. After the guard statement, create and return a Food object.
struct Food {
var name: String
var calories: Int
}
let foodTextField = UITextField()
let caloriesTextField = UITextField()
foodTextField.text = "Banana"
caloriesTextField.text = "23"
func logFood() -> Food? {
guard foodTextField.text != nil && caloriesTextField.text != nil else { return nil }
let specificFood = Food(name:foodTextField.text!, calories: Int(caloriesTextField.text!)!)
print(specificFood.name+" "+String(specificFood.calories))
return specificFood
}
logFood()