首页 > 编程语言 > 详细

Swift 函数

时间:2019-08-08 19:03:50      阅读:103      评论:0      收藏:0      [点我收藏+]

1、函数的定义

func test() ->Void{
    print("test")
}

func test() {
    print("test")
}
func test() ->(){
    print("test")
}
func pi() -> Double {
    return 3.14
}

2、隐式返回

func sum (v1 :Int , v2: Int) -> Int{
    return v1+v2;
}
//形参默认是let 也只能是let
func sum (v1 :Int , v2: Int) -> Int{
     v1+v2;
}

3、元组返回、实现多返回值

func calcute(v1 :Int , v2: Int) ->(sum:Int,cha:Int,avg:Double){
    return (v1+v2,v1-v2,Double((v1+v2))/2.0)
}

print(calcute(v1: 2, v2: 3))
print(calcute(v1: 2, v2: 3).sum)
print(calcute(v1: 2, v2: 3).cha)
print(calcute(v1: 2, v2: 3).avg)

4、参数标签

func gotoWork( time:Int) ->(){
    print("gotoWork:\(time)点")
}
//参数标签
func gotoWork(at time:Int) ->(){
    print("gotoWork:\(time)点")
}

gotoWork(at: 8)
//使用下划线省略参数标签
func sum (_ v1 :Int ,_ v2: Int) -> Int{
    return v1+v2;
}

print(sum(3, 3))

5、默认参数值

func person (name : String="nobody" , age: Int = 50 ,weight:Double) {
    print("name:\(name)  age\(age)  weight:\(weight)")
}
person(name: "jack", age: 18, weight: 99.5)
person(weight: 33)
person(name: "tom", weight: 12)
// 输出
//name:jack  age18  weight:99.5
//name:nobody  age50  weight:33.0
//name:tom  age50  weight:12.0

6、可变参数

func sum (numbers : Int...)->(Int){
    var s = 0
    
    for i in numbers {
        s+=i
    }
    return s
}

print(sum(numbers: 1,2,3,4))  //10
// 注意 一个函数只有有一个可变参数 并且紧跟着的第一个 参数标签不能省略
func test (numbers: Int... , name:String ,_ age :Int){
    print("number:\(numbers) name:\(name) age:\(age)")
}
test(numbers: 1,3,5, name: "jack", 20)
//输出 number:[1, 3, 5] name:jack age:20

6、Swift 自带的 print 函数

/// - Parameters:
///   - items: Zero or more items to print.
///   - separator: A string to print between each item. The default is a single
///     space (`" "`).
///   - terminator: The string to print after all items have been printed. The
///     default is a newline (`"\n"`).
//public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
// separator 元素分割符  terminator 结尾符号
print(1,2,3,4, separator: "--", terminator: "..")
print(8,9,10, separator: "--", terminator: "..")
//输出 1--2--3--4..8--9--10..

 

Swift 函数

原文:https://www.cnblogs.com/ZhangShengjie/p/11322862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!