swift语法 guard 提前退出

2022-01-29  本文已影响0人  我阿郑

像 if 语句一样,guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码。

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }

    print("Hello \(name)!")

    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }

    print("I hope the weather is nice in \(location).")
}

person["name"] 为空时 就会进入guard语句的else从句执行return

再比如下面的写法:

public func unusedFiles() throws -> [FileInfo] {
       guard !resourceExtensions.isEmpty else {
            throw FengNiaoError.noResourceExtension
        }
        guard !searchInFileExtensions.isEmpty else {
            throw FengNiaoError.noFileExtension
        }

        let allResources = allResourceFiles()
        let usedNames = allUsedStringNames()
        
        return FengNiao.filterUnused(from: allResources, used: usedNames).map( FileInfo.init )
}

resourceExtensions.isEmptytrue时就会进入 else从句执行 throw Error

上一篇 下一篇

猜你喜欢

热点阅读