Funciones en Swift - Desarrolladores iOS: Desde Objective-C hasta Swift

Blog sobre Optimizacion Avanzado y Desarrolladores iOS: Desde Objective-C hasta Swift en Estados Unidos

La definición de Función en Swift es diferente a la de C. Una muestra de definición de función es la siguiente:

func someFunction(s:String, i: Int) -> Bool
{
...    // code    
}
Las funciones Swift son tipos de primera clase. Esto quiere decir que puedes asignar funciones a las variables, hacerlas pasar como parámetros para las funciones o hacerlas regresar tipos:

func stringLength(s:String) -> Int
{
    return countElements(s)
}

func stringValue(s:String) -> Int
{
    if let x = s.toInt()
    {
        return x
    }
    return 0
}

func doSomething(f:String -> Int, s:String) -> Int
{
    return f(s).successor()
}

let f1 = stringLength
let f2 = stringValue

doSomething(f1, "123")    // 4
doSomething(f2, "123")    // 124
De nuevo, Swift infiere los tipos de f1 and f2 (String -> Int), Aunque los pudimos haber definido explícitamente:

let f1:String -> Int = stringLength
Las funciones también pueden regresar otras funciones:

func compareGreaterThan(a: Int, b: Int) -> Bool
{
    return a > b
}

func compareLessThan(a: Int, b: Int) -> Bool
{
    return a < b
}

func comparator(greaterThan:Bool) -> (Int, Int) -> Bool
{
    if greaterThan
    {
        return compareGreaterThan
    }
    else
    {
        return compareLessThan
    }
}

let f = comparator(true)
println(f(5, 9))

Visitar articulo completo sobre Desarrolladores iOS: Desde Objective-C hasta Swift

Comparte tu opinion o comenta

Cuenta tu opinion o amplia el contenido del articulo
Enviado por khadim hussain 04/11/2019
http://www.aiobjectives.com worldwide.Technology, especially artificial intelligence has made our lives really easy. From the general apps to Alexa in our houses technology has seeped in even without us realizing when this happened. Here is a quick view of future where AI will have significant role in each phase of our life.Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. ... These apps are licensed by manufacturers of Android devices certified under imposed by Google
Enviado por khadim hussain 04/11/2019
http://www.aiobjectives.com worldwide.Technology, especially artificial intelligence has made our lives really easy. From the general apps to Alexa in our houses technology has seeped in even without us realizing when this happened. Here is a quick view of future where AI will have significant role in each phase of our life.Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. ... These apps are licensed by manufacturers of Android devices certified under imposed by Google