Last active
March 13, 2018 08:44
-
-
Save hmhmsh/9d937cdb81eb941ee5035e74e18dcc77 to your computer and use it in GitHub Desktop.
forループの中でcontinueやbreakを使用しているのを、filterに書き換える
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 array = [0, 2, 0, 2, 2, 1, 2, 2] | |
// flatMap({$0})を入れないと、コンパイルエラー | |
// AnySequenceとArrayで同じprefix()メソッドがあり、どちらを使用するのかが曖昧のため、コンパイルエラーになる | |
let map = array.prefix(while: {$0 != 1}).flatMap({$0}).filter( {$0 == 2} ) | |
print(map) // [2, 2, 2] | |
// filterの中で何かして、結果に反映するかの判断するには、このようにすることができる | |
// つまり、continueを使用していたところは、return falseにすることができる | |
let map = array.prefix(while: {$0 != 1}).flatMap({$0}).filter( { | |
if $0 == 2 { | |
return true | |
} else { | |
return false | |
} | |
} ) | |
print(map) // [2, 2, 2] |
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 array = [0, 2, 0, 2, 2, 1, 2, 2] | |
var map = [Int]() | |
for i in array { | |
if i == 2 { | |
map.append(i) | |
} else if i == 1 { | |
break | |
} else { | |
continue | |
} | |
} | |
print(map) // [2, 2, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment