Blaska
Blaska

Reputation: 1

How to refactor two for loop using map method

I'm using swiftyjson library and I wrote this to retrieve urlImage.

    for (_, value) in json["assets"] {
        for item in value.arrayValue {
            let urlImage = item["urlImage"].stringValue
        }
    }

I want to refactor using flat method. Any suggestions?

Upvotes: 0

Views: 217

Answers (2)

Fabian
Fabian

Reputation: 5348

Here is the way using flatMap and map. Two maps are necessary since it is necessary to iterate over two arrays. $0 is the standard argument name in a closure if it is not named like { arg in.

let urlImages: [String] = jsonObject["assets"].arrayValue.flatMap{
    $0.arrayValue.map{ $0["urlImage"].stringValue }
}

And with filtering out empty urlImages:

let z: [String] = jsonObject["assets"].flatMap{
    $1.compactMap{
        let urlImage = $1["urlImage"].stringValue
        return urlImage == "" ? nil : urlImage
    }
}

let z2: [String] = jsonObject["assets"].flatMap{
    $1.compactMap{ $1["urlImage"].stringValue }.filter{ $0 != "" }
}

Upvotes: 1

ielyamani
ielyamani

Reputation: 18591

Easy:

let urlImageArray = json["assets"].map{$1}.map{$0["urlImage"].stringValue}

Upvotes: 2

Related Questions