typestar

Colecciones mutables en Objective-C

Las clases mutables heredan de las inmutables y agregan escritores.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // Mutable classes subclass the immutable ones and add writers.
        NSMutableArray<NSString *> *wants =
            [@[ @"Blue Train", @"Nefertiti" ] mutableCopy];
        [wants addObject:@"Speak No Evil"];
        [wants removeObject:@"Nefertiti"];
        NSLog(@"Want list: %@", [wants componentsJoinedByString:@", "]);

        NSMutableDictionary<NSString *, NSNumber *> *prices =
            [[NSMutableDictionary alloc] init];
        prices[@"Blue Train"] = @29;
        prices[@"Speak No Evil"] = @24;
        [prices removeObjectForKey:@"Blue Train"];
        NSLog(@"Priced titles: %lu", (unsigned long)[prices count]);
    }
    return 0;
}

Cómo funciona

  1. mutableCopy vuelve editable un literal.
  2. addObject: y removeObject: remodelan el arreglo.
  3. La asignación por subíndice escribe en un diccionario mutable.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
624
Tokens
135
Ritmo de tres estrellas
60 tpm

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

Escribe este fragmento

Paso 3 de 3 en Colecciones; paso 12 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →