return
return 用于从函数中返回值。
基本形式
func add(x: int, y: int) -> int {
return x + y;
}
规则
return expr;的类型必须与函数返回类型一致- 返回
unit的函数允许写return; - 非
unit函数不能写裸return;
尾表达式
函数体最后一个不带分号的表达式也可以作为返回值:
func add(x: int, y: int) -> int {
x + y
}
示例
func classify(x: int) -> string {
if x < 0 {
return "negative";
}
if x == 0 {
return "zero";
}
"positive"
}