LoginSignup
10
8

More than 5 years have passed since last update.

Swift 3.1: prefix(while:_) / drop(while:_) の使い方

Posted at

TL;DR

Swift 3.1 で Sequence に追加されたAPI。
Haskellにおける takeWhiledropWhile

let isEven: ((Int) -> Bool) = { $0 % 2 == 0 }
let xs = [2, 4, 6, 1, 3, 8]
xs.prefix(while: isEven) // => [2, 4, 6]
xs.drop(while: isEven)   // => [1, 3, 8]

Trailing Clojure

xs.prefix { $0 % 2 == 0 }  // => [2, 4, 6]
xs.drop   { $0 % 2 == 0 }  // => [1, 3, 8]

文字列で使ってみる

let s = "Hello world!"
String(s.characters.prefix { $0 != " " }) // => "Hello"
String(s.characters.drop   { $0 != " " }) // => " world!"

参考

終わり

最近Qiita投稿してなかったので軽いものを書いてみました。
個人的にはやっぱりtakeWhileなのですけれども。

10
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8