Missing return in a function expected to return 'Double?'

后端 未结 3 1530
后悔当初
后悔当初 2021-01-29 07:52

I\'m grinding through Apple\'s App Development with Swift book and I have been having a few issues with the Optionals sections.

I\'m getting stuck accessing a dictionary

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-29 08:56

    The problem is merely that you have not covered all cases in your logic. What if name is not greater than zero? Your code does not say what to do. Thus you fail to return a value in that situation:

    func priceCheck(name: String) -> Double? {
        let pricefinder = name
        if let name = stock[name] {
            print(name)
            if name > 0 {
                if let pricefinder = prices[pricefinder] {
                    print(pricefinder)
                    return pricefinder
                } else {
                    return nil
                }
            } else { // this is the question: what if it isn't?
                return nil // ???? I don't know what you want to do...
                // ... but you MUST return something in this situation
            }
        } else {
            return nil
        }
    }
    

    Listen to the compiler. It knows more than you do.

提交回复
热议问题