swift中方法参数与返回值

时间:2021-11-20 12:06:37
//: Playground - noun: a place where people can play

import UIKit

//标签:break可以跳出指定循环
group :
for _ in 1...2 {
for _ in 1...3 {
print("俯卧撑一次")
break
}
print("休息一次")
}


/// 求两数的和
///
/// - parameter num1: 数字1
/// - parameter num2: 数字2
///
/// - returns: 返回两个数的和
func sum(num1: Int, num2: Int) -> Int{
return num1 + num2;
}
print(sum(num1: 1, num2: 2))


/// 没有返回值函数,写法1
///
/// - parameter starNum: *号数量
func printStar (starNum: Int) -> Void {
for _ in 1...starNum {
print("*")
}
}
printStar(starNum: 3)

/// 没有返回值函数,写法2
///
/// - parameter starNum: *号数量
func prinrStar2 (starNum: Int) -> (){
for _ in 1...starNum {
print("**")
}
}
prinrStar2(starNum: 4)

/// 没有返回值函数,写法3
///
/// - parameter starNum: *号数量
func printStar3 (starNum: Int) {
for _ in 1...starNum {
print("***")
}
}
printStar3(starNum: 5)

/// 返回元组
///
/// - parameter id: 人物id
///
/// - returns: 返回人物的姓名和年龄
func getPoint(stu_id id: Int) -> (name: String, age: Int) {
if id > 0 {
return ("jack", 20)
} else {
return ("no", 0)
}
}
var people = getPoint(stu_id: 10)
print("name=\(people.name), age=\(people.age)")

/// 默认参数
///
/// - parameter name: 姓名
/// - parameter age: 年龄
func student (name: String, _ age: Int = 20) {
print("name=\(name), age=\(age)")
}
student(name: "jack")

/// 变量参数
///
/// - parameter srcStr: 源字符串
/// - parameter addStr: 加字符串
/// - parameter num: 数量
///
/// - returns: 返回字符串
func append ( srcStr: String, addStr: String, num: Int) -> String {
var srcStr = srcStr
for _ in 1...num {
srcStr += addStr
}
return srcStr
}
append(srcStr: "jack", addStr: ".", num: 4)