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

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

提交回复
热议问题