Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

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

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 after I have accessed another dictionary to return an optional value that meets a condition. The error being returned is:

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

var prices = ["Chips": 2.99, "Donuts": 1.89, "Juice": 3.99, "Apple": 0.50, "Banana": 0.25, "Broccoli": 0.99]
var stock = ["Chips": 4, "Donuts": 0, "Juice": 12, "Apple": 6, "Banana": 6, "Broccoli": 3]

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
    }
}

Where am I going wrong with the code above? I need to check if a product is in stock and then return its price if that condition evaluates to true.

And is there a more elegant solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...