Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

swift Arrayでwhereを使う

swiftはモダンな言語なので、C言語風の書き方は極力排除されている。
Arrayでwhereがついているメソッドを使い条件式を表すクロージャを指定して結果を取得するケースは多い。

public struct Array<Element> : RandomAccessCollection, MutableCollection {

    // 条件を満たす最初の要素インデックス
    // 条件を満たす要素がない場合はnilを返す
    public func index(where predicate: (Element) throws -> Bool) rethrows -> Int?

    // 条件を満たす要素が存在する
    // 存在が確定した時点で以降の判定は行われない
    public func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool

    // 条件を満たす最初の要素
    // 条件を満たす要素がない場合はnilを返す
    public func first(where predicate: (Element) throws -> Bool) rethrows -> Element?

    // 条件を満たす要素の配列を返す
    public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
}

extension Array where Element == String {

    /// Returns a new string by concatenating the elements of the sequence,
    /// adding the given separator between each element.
    ///
    /// The following example shows how an array of strings can be joined to a
    /// single, comma-separated string:
    ///
    ///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    ///     let list = cast.joined(separator: ", ")
    ///     print(list)
    ///     // Prints "Vivien, Marlon, Kim, Karl"
    ///
    /// - Parameter separator: A string to insert between each of the elements
    ///   in this sequence. The default separator is an empty string.
    /// - Returns: A single, concatenated string.
    public func joined(separator: String = default) -> String
}