149
147

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftの個人的逆引き

Last updated at Posted at 2016-01-17

一度使った書き方などをメモっていく場所。

※ 記事の簡潔さを優先して非省略形はあえて記載しません。
※ $R0:などは実行結果です。


for-each

[1,2,3].forEach{ print($0) }

for-each(indexも使う)

let a = [1,2,3]
zip(a.indices, a).forEach {
	print("\($0)-\($1)")
}

文字列から改行を取り除く(filterで)


//swift3
let str = String("a\nb\r".characters.filter { !"\n\r".characters.contains($0) })

//swift4以降
let str = String("a\nb\r".filter { !"\n\r".contains($0) })

=> str: String = "ab"

文字列をセパレータで分割して配列にする

//swift3
"1,2,3".characters.split(separator: ",").map(String.init)

//swift4以降
"1,2,3".components(separatedBy: ",")

$R17: [String] = 3 values {
  [0] = "1"
  [1] = "2"
  [2] = "3"
}

配列要素の存在チェック

[1,2,3].contains(3)
$R0: Bool = true

[1,2,3].contains(8)
$R1: Bool = false

配列から最大値/最小値を得る

[1,2,3].min()
$R0: Int? = 1

[1,2,3].max()
$R1: Int? = 3

配列から要素を削除

var ary = [1,2,3]

// 先頭の要素を削除、戻り値は削除されたElement
ary.removeFirst()

// 末尾の要素を削除、戻り値は削除されたElement
ary.removeLast()

// 全要素を削除、戻り値は無し
ary.removeAll()

配列要素全てに処理を行い新しい配列を生成

// Ms.を追加
["Rinda","Cathy"].map{ "Ms." + $0 }

$R0: [String] = 2 values {
  [0] = "Ms.Rinda"
  [1] = "Ms.Cathy"
}

// 2をかける
[1,2,3].map{ $0 * 2 }

$R0: [Int] = 3 values {
  [0] = 2
  [1] = 4
  [2] = 6
}

// 2乗
import Foundation

[1,2,3].map{ pow(Double($0), 2) }
$R0: [Double] = 3 values {
  [0] = 1
  [1] = 4
  [2] = 9
}

配列要素の総和を求める(reduceで)

/// 第1引数は初期値
[1,2,3].reduce(0, +)

$R0: Int = 6

配列要素の総乗を求める(reduceで)

/// 第1引数は初期値
[2,3,4].reduce(1, *)
$R0: Int = 24

配列で数値に変換できる要素のみで総和を求める


//swift4.1以降
["1","2","3","a"].compactMap{ Int($0) }.reduce(0, +)

//swift4.0まで
["1","2","3","a"].flatMap{ Int($0) }.reduce(0, +)
$R21: Int = 6  

配列要素をセパレータで連結する

["a","b","c"].joined(separator: ",")
$R15: String = "a,b,c"

数値と文字列が混在する配列から数値のみの配列を得る


//swift4.1以降
["1","2","a"].compactMap{ Int($0) }

//swift4.0まで
["1","2","a"].flatMap{ Int($0) }

$R0: [Int] = 2 values {
  [0] = 1
  [1] = 2
}

配列からnilを除去

//swift4.1以降
 ["1","2",nil].compactMap{$0}

//swift4.0まで
 ["1","2",nil].flatMap{$0}

配列から条件に一致する要素のインデックスを得る

[1,2,3].index{ $0 == 1 }
$R24: Array.Index? = 0


配列から条件に一致する新しい配列を得る

[1,2,3,4,0].filter{ $0 % 2 == 0 && $0 > 0 }

$R0: [Int] = 2 values {
  [0] = 2
  [1] = 4
}

配列を降順ソート/昇順ソート

//これは降順ソート(昇順は<)
 [2,3,1].sorted(by: >)
$R26: [Int] = 3 values {
  [0] = 3
  [1] = 2
  [2] = 1
}

辞書をソート


//keyで昇順ソート
var dic1 = [10 : 1, 8 : 2, 3 : 3, 4 : 7]

dic1.sorted(by: {$0.0 < $1.0 })
$R33: [(key: Int, value: Int)] = 4 values {
  [0] = {
    key = 3
    value = 3
  }
  [1] = {
    key = 4
    value = 7
  }
  [2] = {
    key = 8
    value = 2
  }
  [3] = {
    key = 10
    value = 1
  }
}

// valueで昇順ソート
dic1.sorted(by: {$0.1 < $1.1 })  

破壊的ソート

var ary = [1,2,3]
ary.sort(by: >)
ary

$R0: [Int] = 3 values {
  [0] = 3
  [1] = 2
  [2] = 1
}

構造体のプロパティのみの配列を作る


struct User {
     let id: Int
     init(_ id: Int) {
         self.id = id
     }
 }
let users = [User(1), User(2), User(3)]

//swift5.2以降
let ids = users.map(\.id)
ids
$R0: ids: [Int] = 3 values {
  [0] = 1
  [1] = 2
  [2] = 3
}

//swift5.1まで
users.map{ $0.id }

2秒後に遅延処理

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { 
    // do staff
})

メインスレッドで処理を実行

DispatchQueue.main.async(execute: {
    // do staff					
})

並列に反復処理を実行

DispatchQueue.concurrentPerform(iterations: 10) { (i) in
    print(i)
}

// 結果の一例
0
2
3
4
5
1
7
8
9
6

実行時の値の型を表示

print(type(of: "abc")) // String
print(type(of: 1))     // Int

変数のアドレスを表示 (参考情報のみ)

API for binding memory types and pointer conversion

Swift3.0版、Enumのcaseを配列で返すProtocol Extension


参考

Swift文字列操作用のライブラリ

Swift String Cheat Sheet

10 Swift One Liners To Impress Your Friends

Swift 2.0の新しいflatMapが便利過ぎる

149
147
0

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
149
147

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?