如何在Swift中创建一个具有throw并返回值的函数?

huangapple go评论71阅读模式
英文:

how can I create a function with throw and return a value in swift?

问题

我是新手使用Swift。我尝试理解带有"throw"的函数。是否可能让函数抛出异常并同时返回一个值?

func throwAndReturnString() {
    guard let response = internalFunction else {
        throw "response should not be nil"
    } 
    return response.label
}
英文:

I am new on swift. I try to understand the function with throw. is it possible to make the function throw and at the same function return a value?

func throwAndReturnString() {
    guard let response = internalFunction else {
        throw "response should not nil"
    } 
    return response.label
}

答案1

得分: 1

以下是翻译好的部分:

要使一个可以throw的函数,需要在其前加上throws修饰词,并且在签名中添加返回类型。

func throwAndReturnString() throws -> String { //<<--HERE

这假设label是一个String

英文:

To have a function that can throw it needs to be decorated with throws and to return the type needs to be added to the signature.

func throwAndReturnString() throws -&gt; String { //&lt;&lt;--HERE

This assumes that label is a String

huangapple
  • 本文由 发表于 2023年4月11日 05:04:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定