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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。