Swiftのビルトイン関数の使い方リファレンス


スポンサーリンク

abs(x: T) -> T

  • 絶対値を返す
abs(-10)
// r4 : Int = 10
abs(46.89)
// r6 : Double = 46.89

assert(condition: @auto_closure () -> Bool, message: StaticString, file: StaticString, line: UWord)

  • 条件が成り立っていることをチェックする
  • Xcodeから実行した場合は、どのassertで終了したのかわかり、メッセージが出力される
let x = 3
assert(x == 3)
assert(1 == 3)
assertion failed: file <REPL Input>, line 1
Segmentation fault: 11

contains(sequence: S, item: S.GeneratorType.Element)

  • sequenceの中にitemが含まれているか
let favoriteLanguages = ["c++", "Ruby", "Lisp", "Swift"]
contains(favoriteLanguages, "Java")
// r0 : Bool = false

contains(sequence: S, predicate: (S.GeneratorType.Element) -> L)

  • sequenceの中にpredicateを真にする要素が含まれているか
let favoriteLanguages = ["c++", "Ruby", "Lisp", "Swift"]
contains(favoriteLanguages) { $0.hasPrefix("S") }
// r0 : Bool = true

countElements(x : T) -> T.IndexType.DistanceType

  • xの中の要素数を返す。
  • IndexTypeが
    • RandomAccessIndexなら、O(1)
    • でなければ、O(N)
(swift) let favoriteLanguages = ["c++", "Ruby", "Lisp", "Swift"]
// favoriteLanguages : Array<String> = ["c++", "Ruby", "Lisp", "Swift"]
(swift) countElements(favoriteLanguages)
// r0 : Int = 4

distance(start: T, end: T) -> T.DistanceType

  • 2点の距離を返す
  • abs(start - end)と同じ
  • 1次元の距離しか出来ないみたい
(swift) distance(1,2)
// r1 : Int = 1
(swift) distance(-1,2)
// r2 : Int = 3
(swift) distance((-1,-1),(2,2))
<REPL Input>:1:1: error: cannot convert the expression's type '$T2' to type '_BuiltinIntegerLiteralConvertible'
distance((-1,-1),(2,2))
^~~~~~~~~~~~~~~~~~~~~~~
(swift) distance([-1,-1],[2,2])
<REPL Input>:1:1: error: cannot convert the expression's type '$T2' to type '_BuiltinIntegerLiteralConvertible'
distance([-1,-1],[2,2])
^~~~~~~~~~~~~~~~~~~~~~~
(swift) distance("a", "b")
<REPL Input>:1:1: error: cannot convert the expression's type '$T2' to type '_BuiltinIntegerLiteralConvertible'
distance("a", "b")


スポンサーリンク

dropFirst(sequence: Seq)

  • sequenceから最初の要素を除いた新しいシーケンス(配列など)を返す
var src = [1, 2, 3]
dropFirst(src)
// r1 : Slice<Int> = [2, 3]
src
// src : Array<Int> = [1, 2, 3]

dropLast(sequence: Seq)

  • sequenceから最後の要素を除いた新しいシーケンス(配列など)を返す
var src = [1, 2, 3]
// src : Array<Int> = [1, 2, 3]
(swift) dropLast(src)
// r0 : Slice<Int> = [1, 2]
(swift) src
// src : Array<Int> = [1, 2, 3]

dump(obj: T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

  • オブジェクトの中身を標準出力に出力する
(swift) let favoriteLanguages = ["c++", "Ruby"]
// favoriteLanguages : Array<String> = ["c++", "Ruby"]
(swift) dump(favoriteLanguages)
▿ 2 elements
  - [0]: c++
  - [1]: Ruby
// r1 : Array<String> = ["c++", "Ruby"]

enumerate(seq : Seq)

  • seqをイテレートするときに使う
  • インデックスと値のタプルを返す
(swift) let favoriteLanguages = ["c++", "Ruby", "Lisp", "Swift"]
// favoriteLanguages : Array<String> = ["c++", "Ruby", "Lisp", "Swift"]
(swift) for (index, languageName) in enumerate(favoriteLanguages) {
          println(languageName)
        }

equal(sequence1: S1, sequence2: S2)

  • sequence0とsequence1が各要素に同じ値をもつならtrue
let favoriteLanguages = ["c++", "Ruby"]
let availableLanguage = ["c++", "PHP"]
(swift) equal(favoriteLanguages, availableLanguages)
// r2 : Bool = false
(swift) equal("c++", "c+-")
// r1 : Bool = false

filter(source: C, includeElement: (C.GeneratorType..Element) -> Bool)

  • sequenceの要素の中でクロージャーincludeConditionがtrueを返すものから成るシーケンスを返す
let filtered = filter([1,2,3,4]) { $0 % 2 == 0 }
for item in filtered { dump(item); }
- 2
- 4

find(domain: C, value: C.GeneratorType.Element) -> C.IndexType?

  • domainの中で(最初の)valueのインデックスを返す。なければ、nil
find(["a", "b", "c", "b"], "b")
// r6 : Int? = 1
find(["a", "b", "c"], "x")
// r7 : Int? = nil


スポンサーリンク

indices(seq : Seq)

  • seqのインデックス列のRangeオブジェクトを返す
(swift) for index in indices(favoriteLanguages) {
          println("#\(index): " + favoriteLanguages[index])
        }
#0: c++
#1: Ruby

join(separator : C, seq : S) -> C

  • シーケンスseqの要素の間にseparatorを差し込んだ結果の型Cのコレクションを返す
(swift) join(":", ["x", "y"])
// r3 : String = "x:y"
(swift) join([0], [[1],[2],[3]])
// r2 : Array<Int> = [1, 0, 2, 0, 3]

map(source : C, transform : (C.GeneratorType.Element) -> T) -> [T]

  • sourceの各要素にプロシージャーtransformを適用した結果の配列を返す
(swift) for converted in map([1,2,3], { $0 * $0 }) {
          println(String(converted))
        }
1
4
9

max(x: T, y: T, z: T, rest: T...) -> T

  • 引数の中の最大値を返す
max(4.0, 9.0, 5.0, 5.2)
// r16 : Double = 9.0
max("a", "b", "c")
// r18 : String = "c"

maxElement(range: R) -> R.GeneratorType.Element

  • 最大の要素を返す
  • 空のsequenceはエラーになる(バグかも)
(swift) let x1 = [1,3,2]
// x1 : Array<Int> = [1, 3, 2]
(swift) maxElement(x1)
// r0 : Int = 3
(swift) let x2 : Int[] = []
// x2 : Int[] = []
(swift) maxElement(x2) // コケる

min(x: T, y: T, z: T, rest: T...)

  • 引数の中の最小値を返す
(swift) min(4.0, 9.0, 5.0, 5.2)
// r20 : Double = 4.0
(swift) min("a", "b", "c")
// r21 : String = "a"

minElement

  • 最小の要素を返す
  • 空のsequenceはエラーになる(バグかも)
(swift) minElement(["a", "b", "c"])
// r22 : String = "a"
(swift) let x2: Int[] = []
// x2 : Int[] = []
(swift) minElement(x2)
fatal error: Can't unwrap Optional.None

print

  • 説明省略

println

  • 説明省略

reduce(sequence: S, initial: U, combine: (U, S.GeneratorType.Element) -> U)

  • 説明が難しいのですが、等価な関数を書くとすれば、こんな感じです。
func reduce(sequence, seed, proc)
  var x = seed
  for item in sequence {
    x = proc(x, item)
  }
  return x
}
(swift) let sum = reduce([1, 2, 3], 0, { $0 + $1 })
// sum : Int = 6
(swift) let max = reduce([2, 3, 1], Int.min, { $0 < $1 ? $1 : $0 })
// max : Int = 3

reverse(source: C) -> [C.GeneratorType.Element]

  • 要素を逆順にした配列を返す
(swift) for item in reverse(["a", "b", "c"]) {
          println(item)
        }
c
b
a

startsWith(s: S0, prefix: S1)

  • sがprefixの要素の並びから始まればtrue
(swift) startsWith("grapefruits", "grape")
// r25 : Bool = true
(swift) startsWith([4, 6, 8, 9], [4, 6])
// r26 : Bool = true

sort()

  • 説明省略