iOSDev
iOSDev

Reputation: 199

How to use Pattern matching in a Swift for loop for nested array

For a simple for loop we can use pattern matching like this

let arr1 = ["a", true, 1, 5.0]
for case let str as String in arr1 {
    print(str)
}

How to get the string from a nested array without nested for loop?

let arr2 = [["a", true, 1, 5.0],
            ["b", true, 2, 15.0], 
            ["c", false, 31, 12.0]]

The inner array's first object is string always

Upvotes: 0

Views: 166

Answers (2)

Vasilis D.
Vasilis D.

Reputation: 1456

You can do that by using the compact map function if you know that the first object of your array is string and you are interested only for your first item.

Example:

let arr2 = [["a", true, 1, 5.0],
            ["b", true, 2, 15.0],
            ["c", false, 31, 12.0]]

printStrings(strArrayOfArray: arr2)

func printStrings(strArrayOfArray: [[Any]]) {
print(strArrayOfArray.compactMap({ (anyArray) -> String? in
    if let str = strArrayOfArray.first?.first as? String {
        return str
    } else {
        return nil
    }
}))

}

Output:

["a", "a", "a"]

Upvotes: 1

vadian
vadian

Reputation: 285180

Not really pattern matching but without a loop

arr2.compactMap{$0.first{$0 is String}}.forEach{print($0)}

compactMap is necessary because first returns an optional. The position of the String in the array is irrelevant.

Upvotes: 1

Related Questions