大橙子网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Swift函数类型

    函数可以作为一种类型使用,作为类型与其它数据类型没有区别:

创新互联于2013年创立,是专业互联网技术服务公司,拥有项目成都网站设计、做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元乡宁做网站,已为上家服务,为乡宁各地企业和个人服务,联系电话:028-86922220

    有如下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)

                


网站名称:Swift函数类型
文章分享:http://dzwzjz.com/article/jdopgd.html
在线咨询
服务热线
服务热线:028-86922220
TOP