2016-03-29 13 views
5

Sto applicando una mappa a un dizionario che contiene try. Vorrei saltare l'iterazione se l'elemento mappato non è valido.Salta la voce durante l'esecuzione della mappa in Swift?

Ad esempio:

func doSomething<T: MyType>() -> [T] 
    dictionaries.map({ 
     try? anotherFunc($0) // Want to keep non-optionals in array, how to skip? 
    }) 
} 

Nell'esempio di cui sopra, se i rendimenti anotherFuncnil, come sfuggire l'iterazione corrente e passare a quello successivo? In questo modo, non conterrebbe gli articoli che sono nil. È possibile?

risposta

15

Basta sostituire map() da flatMap():

extension SequenceType { 
    /// Returns an `Array` containing the non-nil results of mapping 
    /// `transform` over `self`. 
    /// 
    /// - Complexity: O(*M* + *N*), where *M* is the length of `self` 
    /// and *N* is the length of the result. 
    @warn_unused_result 
    public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T] 
} 

try? ... rendimenti nil se la chiamata genera un errore, così quei elementi verrà omessa nel risultato.

Un esempio di self-contained solo a scopo dimostrativo:

enum MyError : ErrorType { 
    case DivisionByZeroError 
} 

func inverse(x : Double) throws -> Double { 
    guard x != 0 else { 
     throw MyError.DivisionByZeroError 
    } 
    return 1.0/x 
} 

let values = [ 1.0, 2.0, 0.0, 4.0 ] 
let result = values.flatMap { 
    try? inverse($0) 
} 
print(result) // [1.0, 0.5, 0.25] 

Per Swift 3, sostituire ErrorType da Error.

+0

Grazie per avermi permesso di scoprire 'flatMap'! Ho appena notato che non funziona con i dizionari tho. – TruMan1

+2

@ TruMan1: Sono abbastanza sicuro che lo faccia. Sia 'map' che' flatMap' possono essere applicati a un dizionario. La chiusura viene chiamata con chiave/valore come argomenti. –

+0

Hai ragione dispiace, grazie ancora !! – TruMan1

Problemi correlati