Swift函數類型

來源:互聯網
上載者:User

標籤:swift函數類型

    函數可以作為一種類型使用,作為類型與其它資料類型沒有區別:


    有如下3個函數的定義:


    (1)func rectangleArea(width : Double, height : Double ) -> Double {

            let area = width * height

            return area


}


      (2)func triangleArea(bottom : Double, height : Double ) -> Double {

            let area = 0.5 * bottom *  height

            return area


}


        (3)func sayHello(){

            println("Hello World")


}


        第一個和第二個函數的傳回型別都是(Double,Double) -> Double,第三個函數返回的類型為() ->()



        函數作為參數類型使用:可以把函數的類型作為另一個函數的傳回型別使用:


        樣本:


            

         func rectangleArea(width : Double, height : Double ) -> Double {

            let area = width * height

            return area


}



        func triangleArea(bottom : Double, height : Double ) -> Double {

            let area = 0.5 * bottom *  height

            return area


}



             func getArea(type : String) -> (Double,Double) ->Double {

                        var returnFunction :(Double,Double) -> Double


                            switch type {

                                case "rect":

                                        returnFunction = rectangleArea

                                case "tria" :


                                        return triangleArea

                                default:

                                        returnFunction = rectangleArea


}

                            return returnFunction

}


                var area = getArea("tria")

                println("TriangleArea:\(area(20,30))")


                

                var area = getArea("rect")

                println("TriangleArea:\(area(20,30))")



        可以把函數類型作為其它函數的參數類型使用:

            

        樣本:

            

     func rectangleArea(width : Double, height : Double ) -> Double {

            let area = width * height

            return area


}



        func triangleArea(bottom : Double, height : Double ) -> Double {

            let area = 0.5 * bottom *  height

            return area


}



          func getAreaByFunc(funcName : (Double,Double) -> Double, a: Double,b: Double) -> Double {


                var area = funName(a,b)

                return area

}


            var result :Double = getAreaByFunc(rectangleArea,20,30)


                

本文出自 “平凡之路” 部落格,請務必保留此出處http://linjohn.blog.51cto.com/1026193/1620360

Swift函數類型

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.