typestar

Blocks en Objective-C

Valores de función con la famosa firma de adentro hacia afuera.

#import <Foundation/Foundation.h>

// A typedef tames the block type's inside-out spelling.
typedef NSString *(^Labeler)(NSString *);

int main(void) {
    @autoreleasepool {
        // ^ opens a block literal: a function value with a body.
        Labeler tag = ^NSString *(NSString *title) {
            return [NSString stringWithFormat:@"[USED] %@", title];
        };
        NSLog(@"%@", tag(@"Court and Spark"));

        NSInteger (^discount)(NSInteger) = ^NSInteger(NSInteger cents) {
            return cents * 80 / 100;
        };
        NSLog(@"Sale price: %ld", (long)discount(2499));
    }
    return 0;
}

Cómo funciona

  1. ^NSString *(NSString *title) { ... } es un literal de block.
  2. Un typedef doma la declaración para reusarla.
  3. Los blocks se asignan a variables y se llaman como funciones.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
528
Tokens
111
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 111 segundos.

Escribe este fragmento

Paso 1 de 3 en Blocks; paso 16 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →

Blocks en otros lenguajes