从方法返回选项

时间:2014-06-04 12:44:56

标签: swift

我有一组基本的构造,包括用于定义车库的Garage结构,用于封装硬编码车库列表的Garages类,以及用于搜索的Car类车库基于制造商String。

我的问题是Car.findGarageByManufacturer需要选择性地返回一个Garage实例(如果找不到则返回nil。)但是我收到以下错误:

可选类型“车库?”的值没有打开;你的意思是用'!'要么 '?'吗

...在return foundGarage

如何在方法中返回选项?

// Using a struct because an 'Object' type doesn't seem to exist :-/
struct Garage {
    var name: String
    var manu: String
}

// Hardcorded set of garages, using class to test returning an array of a struct instance.
class Garages {
    func getGarages() -> Array<Garage> {
        var garages: Garage[] = [
            Garage(name: "VW Car Park", manu: "VW"),
            Garage(name: "Williams BMW", manu: "BMW"),
            Garage(name: "Hadwins", manu: "VW")
        ]
        return garages;
    }
}

// Immediately create an instance of the Garages class
let garages = Garages()

class Car {
    func findGarageByManufacturer(manufacturer: String) -> Garage {
        var foundGarage: Garage? = nil
        for garage in garages.getGarages() {
            if(garage.manu == manufacturer) {
                foundGarage = garage
            }
        }
        // This is the line that's causing an error
        // How do we optionally return a garage?
        return foundGarage
    }
}

1 个答案:

答案 0 :(得分:2)

func findGarageByManufacturer(manufacturer: String) -> Garage

必须是

func findGarageByManufacturer(manufacturer: String) -> Garage?

(注意问号)