英文:
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 -> String { //<<--HERE
This assumes that label
is a String
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论