"Pasar de la entrada a la competencia" ~ artículos básicos (flujo de control, función)

Contacto: Shihu QQ: 1224614774 Apodo: Om Mani Padme Hong

                      Grupo QQ: 807236138 Nombre del grupo: grupo de aprendizaje de intercambio de tecnología iOS

                      Grupo QQ: 713799633 Nombre del grupo: grupo de aprendizaje de intercambio de tecnología iOS-2

 

referencia:

"Pasar de entrada a competencia" ~ artículos básicos (tipos de datos) https://blog.csdn.net/shihuboke/article/details/109553998
"pasar de entrada a competencia" ~ artículos básicos (operadores, cadenas) https: // blog.csdn.net/shihuboke/article/details/110203341

 

1. Flujo de control

1. bucle for

    For I in 1…6 { // 遍历闭区间的所有整数

    }

    如果 i 变量用不到可以用下划线“_”代替具体的变量名

    For _ in 1…6 { // 遍历闭区间的所有整数

    }

2. mientras bucle

    while 循环就是重复执行一系列语句,直到条件语句的值为 false

    第一种是 while 循环
    第二种是 repeat-while 循环

    例子:

        while  condition {

            Statements
        }

        repeat {
            Statements
        } while  condition


3. Si declaración condicional

switch 条件语句

    匹配具体值
           例子:
             enum month {
                 case  January
                 case   February
                 case   March
                 case   April
                 case  May
              }

        var curMonth = month.February

        switch  curMonth {
            case  month.January
            case  month.February
            case  month.March
         }

    匹配范围

    例子:
    用上面的源代码

    var curMonth = 5

    switch  curMonth {
        case  1…3
        case  4…6
        case  month.March
      }

    匹配元组值

    var classInfo = (2015, “新年好”)

    switch  classInfo {
        case  (2016,“新年好”)
        case  (2016,_)
        case  (_,“新年好”)
     }


    值绑定
    将 case 语句匹配成功的值绑定到一个临时变量或者常量上。该 case 语句中可以使用该变量或者常量
    例子:
    var classInfo = (2015, “新年好”)

    switch  classInfo {
        case  (let year,“新年好”)print(\(year))
        case  (2016,let name)   print(\(name))
        case  let(year,name)    print(===\(year) === \(name))
    }

  where 语句

  在值绑定的基础上,case 块的匹配引入 where 语句构造复杂的比较语句,成功后执行相应语句
  例子:
    switch  classInfo {
        case  (year,_)where year == 2015
        case  (_, name) where name == “新年好”
        case   let(year,name)     print(===\(year) === \(name))
    }


4. Declaración de transferencia de control

常用的控制转移语句: continue  和 break

    continue : 语句在循环语句中是本次循环结束
    Break : 语句在循序中是直接终止全部后续的循环语句

dos, función

1. Definición de función y método de llamada

函数定义的格式为:

  func funcName(<#parameters#>) -> <#return type#> {

        <#function body#>
    }

  func funcName(parameters: String) -> <#return type#> {

        <#function body#>
    }

2. Parámetros de función

  无形参函数:

    func mulAdd() -> Int {
        let mull : Int
        mull = 2
        return mull
    }

3. Funciones sin valor de retorno

    func mulAdd(mull: Int ,mull2: Int) {

    }

4. Múltiples funciones de valor de retorno

如果函数的返回值为多个,就需要用元组作为返回值类型。

    func climate(city: String) -> (weather:String, wind:String) {

        return (weather, wind)

    }

5. Parámetros variables

Swift还支持形参个数不确定的函数,即在函数定义的时候只知道形参的类型,并不知道形参的个数,只有在调用函数的时候,才能确定形参的个数,这种函数称为可变形参函数

参数类型后面加上”…“,表示该形参为可变形参。

例子:
    func sum(numbers:Int...) -> Int {

        var result = 0

        result += result

        return result
    }
    sum(numbers: 1,2,3,4,5,6)  // 调用

6. parámetros de tipo de entrada y salida

如果要通过函数对传入的变量产生影响时,就需要在函数定义时在形参的类型中加上关键字 inout,表明该参数值得变化会影响传值给它的外部变量,实际上就是通过变量地址实现的

    func swap(a:inout Int,b:inout Int) {

        let temp = a
        a = b
        b = temp
    }

        var a = 5
        var b = 6

        swap(a: &a, b: &b)
        print("a====\(a)")
        print("b====\(b)")

tipo de función

每一个函数都有特定的函数类型,函数类型由形参类型和返回值类型共同组成

    例子:
    // 函数类型
    func add(a:Int ,b: Int) -> Int{

        return a+b
    }

    func helloWorld() {

        print("hello world")
    }

例子中的 add函数类型就是(Int, Int) -> Int 表示该函数有二个 Int 型的形参,返回值为一个 Int 型,

helloWorld 的函数类型比较特殊,因为该函数没有形参,也没有返回值,函数类型就是()->(), 表示该函数没有形参,返回值为 void,相当于一个空元组

2. Variable de tipo de función

函数类型可以像其他数据类型一样使用

       // 函数类型变量
        let mathOperation: (Int,Int)->Int = add
        let mathOperation1 = mathOperation(3,4)
        print(mathOperation1)
        print("mathOperation== \(mathOperation1)")

        //或者

        let operation = add // 简写,因为系统根据推断得到函数类型为(Int,Int)->Int
        let operation1 = operation(6,7)
        print("operation1== \(operation1)")

        //理解”第一个变量的类型是(Int,Int)->Int,就是一个函数类型,表示变量mathOperation为一个函数变量,可以将函数类型为(Int,Int)->Int的函数赋值给他

        let sayOperation : ()->() = helloWorld
        print(sayOperation())

        /** 打印结果

         7
         mathOperation== 7
         operation1== 13
         hello world!
         ()
         */

3. Parámetros del tipo de función

函数类型还可以作为一个函数的参数类型使用

  // 函数类型的参数
    func printResult(operation:(Int,Int)->Int,a:Int, b:Int) {

        let result: Int
        result = operation(a,b)
        print("result === \(result)") // 打印结果 result === 11
    }

      // 函数类型的参数 - 调用
      printResult(operation: add, a: 5, b: 6)

理解: operation:(Int,Int) 定义的是函数类型的参数,用 add 函数 匹配使用

4. El valor de retorno del tipo de función.

函数类型也可以作为另一个函数的返回值类型使用

    // 函数类型的返回值
    func mathOperation2(op:String) -> (Int,Int)->Int {

        if op == "add" {
            return add
        }
    }

     // 函数类型的返回值 - 调用
     let result = mathOperation2(op:"add") // add 是函数
     print("result === \( result(7,8))")  // 打印结果 result === 11


//理解:op:定义字符串,方便传函数名,返回的类型和样式要和 op的类型一致,

      例子:上面 op:"add“ 和 (Int,Int)->Int是一致的

5. Funciones anidadas

在函数体内还可以定义新的函数,称之为嵌套函数,但是只能在函数体内使用,对函数体外是不可见的

例子:
  // 嵌套函数
    func printResult1(a:Int, b :Int) {

        func sub(a: Int,b: Int) -> Int {

            return a - b
        }

        var result3: Int
        result3 = sub(a: a, b: b)
        print("===\(result3)")
    }

     // 调用
     print(printResult1(a: 7, b: 3))

3. Cierre

           Por favor vea el siguiente texto...

 

¡¡¡Gracias!!!

Esta cuenta comparte principalmente mis diversas experiencias y puntos de vista en el proceso de crecimiento, incluidos resúmenes técnicos, artículos técnicos relacionados con iOS, Swift y Mac, recursos de herramientas, participación en debates técnicos, clasificación de habilidades de desarrollo y hacer que aprender sea un placer.

Supongo que te gusta

Origin blog.csdn.net/shihuboke/article/details/112144958
Recomendado
Clasificación