swift基础(三)函数定义

来源:互联网 发布:光圈科技历史知乎 编辑:程序博客网 时间:2024/06/11 01:22

override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

       //函数是执行特定任务的代码自包含块,给定函数名称标示。

        //函数的声明与调用。

       //格式:func函数名(参数名:参数类型)->返回类型。

       //多输入函数:func函数名 (参数名:参数类型,参数名:参数类型)>返回类型

        print(halfOpenRangeLength(0, end: 10))

        print(sayHello("hao"))

        print(sayHelloWorld())

        print(sayGoodBye("neen"))

        if let bounds = conunt([1,2,3,4,5]){

            print(bounds.max,bounds.min)

        }

        

    }

    func sayHello(personName:String) -> String {

        let greeting = "Hello,"+personName+"!"

        return greeting

    }//单输入函数

    func halfOpenRangeLength (start: Int , end: Int) -> Int{

        return end - start

    }//多输入参数

    

    func sayHelloWorld() ->String{

        return"hello,world"

    }//无输入参数

    

    func sayGoodBye(personName:String){

        print("Goodbye,\(personName)")

    }//无返回值函数,其实有返回值,函数没有定义返回类型但返回了一个void类型的特殊值。它是个空的元组,实际上有零个元素的元组,可以写为()

    func conunt(array :[Int]) -> (min:Int,max:Int)?{//注意这里的问号,标明返回值可以为空。

        if array.isEmpty {

            return nil

        }

        var currentMin = array [0]

        var currentMax = array [0]

        for value in array[1..<array.count]{

            if value < currentMin{

                currentMin = value

            }else if value > currentMax {

                currentMax = value

            }

        }

        return (currentMin,currentMax)

    }

0 0
原创粉丝点击