-
-
Save 335g/878572aaf14cbc362d99813611fc2380 to your computer and use it in GitHub Desktop.
memo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let numbers = ["1", "2", "3", "a", "5"]; | |
let only_numbers = numbers.iter() | |
.scan((), |_, &item| item.parse::<i32>().ok()) | |
.collect::<Vec<i32>>(); // [1, 2, 3] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let numbers = ["1", "2", "3", "a", "5"] | |
let onlyNumbers = numbers.flatMap{ Int($0) } // [1, 2, 3, 5] | |
var failed = false | |
let onlyNumbers2 = numbers.reduce(into: [Int]()){ res, item in | |
if !failed, let num = Int(item) { | |
res.append(num) | |
} else { | |
failed = true | |
} | |
} // [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment