功能和可选练习 [英] Functions and optionals exercise

查看:44
本文介绍了功能和可选练习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手.最近,我正在做Swift练习.

I am new to Swift. Recently, I am working on Swift exercises.

想象一下,您正在创建一个用于购物的应用程序.编写一个函数,该函数将带有要购买的商品名称,并返回该商品的成本.在函数的主体中,通过在字典库存中访问来检查该物料是否为库存.如果是,请通过在字典价格中访问该项目来返回该项目的价格.如果该商品缺货,则返回nil.调用该函数并传入下面的词典中存在的String.打印返回值.

Imagine you are creating an app for making purchases. Write a function that will take the name of an item for purchase and will return the cost of that item. In the body of the function, check to see if the item is in stock by accessing it in the dictionary stock. If it is, return the price of the item by accessing it in the dictionary prices. If the item is out of stock, return nil. Call the function and pass in a String that exists in the dictionaries below. Print the return value.

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 purchase(prices:String)->(Int?){
    if stock.index(forKey: prices) == nil{
        return nil
    }else{
        for (String,value) in prices{
            return value
        }
    }
}

我尝试访问stock字典,但是我不知道如何返回给定字符串的结果.

I try to access the stock dictionary, but I don't know how to return the result of the given string.

错误是:

类型'字符串'不符合协议'序列'.

type 'String' does not conform to protocol 'Sequence'.

推荐答案

您所做的完全错误.我建议您先了解基础知识.可以满足以下要求

You are doing it totally wrong. I would suggest you to go through the basics first. The requirement can be met as following

func purchase(item:String)->Double?{
    if let price = prices[item] {
        if let quantity = stock[item] { // check for quantitiy of item
            if quantity == 0 { // item present but 0 quantatiy
                return nil
            }
        } else {
            return nil // item not present in stock
        }
        stock[item] = stock[item]! - 1 // one itme sold
        return price // return the price of the item

    } else {
        return nil // item not present in prices
    }
}

这篇关于功能和可选练习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆