如何开启Playgrounds 学习编程2 参数

2025-10-19 11:55:20

1、假设你正在粉刷房子的墙壁。

你可以使用代码,为你想要使用的四种不同颜色,创建四个不同的粉刷墙壁函数。

paintRoomGreen( )

paintRoomPink( )

paintRoomOrange( )

paintRoomBlue( )

如何开启Playgrounds 学习编程2 参数

2、你可能需要多次调用函数,调用的次数取决于你想要刷多少层。

paintRoomGreen( )

paintRoomGreen( )

paintRoomGreen( )

如何开启Playgrounds 学习编程2 参数

3、与其为每种颜色定义一个不同的函数,不如使用【参数】来制定输入的颜色。

              参数是函数的输入值的名称。

                        ⬇️

func paintRoom(color: Color)

                                  ⬆️

         参数的输入是一种特定的【类型】,如Color(颜色)

如何开启Playgrounds 学习编程2 参数

4、调用函数时:你为每个参数传入【实参】和值,同时函数使用该值来自定它的运行方式。

                          ⬇️

paintRoom( color: red)

如何开启Playgrounds 学习编程2 参数

5、你甚至可以使用好几个参数,传入额外的实参。

paintRoom( color: blue, layers: 3)

                                     ⬆️

现在你可以使用同一个函数,既指定房间要粉刷的颜色,又指定要粉刷的层数!

如何开启Playgrounds 学习编程2 参数

6、func move( distance: Int ) {

                    ⬆️

这个函数有一个Int 类型的【参数】,名为distance。

}

如何开启Playgrounds 学习编程2 参数

7、 func move( distance: Int) {

|--------------------|

|     for i in 1...distance {    |

|         moveForward( )     |  

|     }                              |

| }                                  |

|--------------------|

                 ⬆️

在函数的主体中,【参数】(distance)指定了for 循环运行的次数。

如何开启Playgrounds 学习编程2 参数

8、 func move( distance: Int) {

     for i in 1...distance {

        moveForward( )

     }  

 }

move( distance: 3)

             ⬆️

调用move(distance: )时,传入一个实参,指定你将向前走的步数。

如何开启Playgrounds 学习编程2 参数

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢