温馨提示×

Swift函数类型

发布时间:2020-07-29 07:59:50 来源:网络 阅读:270 作者:hehemmm 栏目:移动开发

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


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


                

推荐内容:05.swift ?可选类型

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

免费拨打  400 100 2938 免费拨打 400 100 2938
24小时售后技术支持 24小时售后技术支持
返回顶部 返回顶部