아래 문제 제대로 푼게 맞을까요?

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()
좋아요 1

struct Food 의 name과 calories 가 optional 이 아니다 보니 Food 를 만들 때 optional이나 nil을 넣을 수 없죠.

if let 구문 등을 이용해 unwarp을 하는 걸 권해드립니다.

Guard Chapter에 있는 lab이니 아래처럼 푸는 건 어떨까요?

아래의 경우 logFood() 에 argument를 넣고 하는게 맞을텐데요… -_- Swift Playground 에서 풀다보면 local변수, global 변수 막 혼동되서 풀고 있네요…logFood()에 argument를 넣는다면 어떻게 처리하고 푸는게 맞나요?

다시 한 번 봐주시겠어요?

struct Food {
    var name: String
    var calories: Int
}

let foodTextField = UITextField()
let caloriesTextField = UITextField()

foodTextField.text = "Banana"
caloriesTextField.text = "23"

func logFood() -> Food? {
    guard let foodName = foodTextField.text else { return nil}
    guard let foodCalorie = caloriesTextField.text else { return  nil}
    
    let specificFood = Food(name:foodName, calories: Int(foodCalorie)!)
    print(specificFood.name+" "+String(specificFood.calories))
    return specificFood
}

func logFood2(foodTextField: UITextField?, caloriesTextField: UITextField?) -> Food? {
    guard let foodName = foodTextField!.text else { return nil}
    guard let foodCalorie = caloriesTextField!.text else { return  nil}
    
    let specificFood = Food(name:foodName, calories: Int(foodCalorie)!)
    print(specificFood.name+" "+String(specificFood.calories))
    return specificFood
}

logFood()
좋아요 1

네, 훨씬 더 좋은 코드인데, guard 문의 return 이전에 에러 메세지를 print 해 주면 더 좋을 듯 합니다.