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

后端 未结 3 1460
后悔当初
后悔当初 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:41

    Your function can be shortened a hell of a lot by taking advantage of some of the tools that’s Swift gives you. Here, take a look, this does the same thing...

    func priceCheck(name: String) -> Double? {
        guard let stockAmount = stock[name],
            stockAmount > 0,
            let price = prices[name] else {
            return nil
        }
    
        return price
    }
    
    0 讨论(0)
  • 2021-01-29 08:49

    As a pretty quick solution, all you have to do is to add return nil at the end of your function:

    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 {
            return nil
        }
    
        // here we go:
        return nil
    }
    

    because at some point (name is not greater than 0), the function does not returns anything.

    Also, note that you could implement your function -as a shorter version- as:

    func priceCheck(name: String) -> Double? {
        let pricefinder = name
        if let name = stock[name], name > 0 {
            if let pricefinder = prices[pricefinder] {
                return pricefinder
            }
        }
    
        return nil
    }
    

    If the function returns nil at the end of it, there is no point of adding else { return nil } for each if; Or you could even use guard statement to achieve it as mentioned in Fogmeister`s answer.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题