目的
これはいろんな言語を渡り歩きすぎて久々に戻ってきた時に
あれ?と思い最初にいつも調べることになる超基本的なところを
メモ書きしているページです。
swiftのバージョンでちょっと変わるかもしれない。
ifの書き方、forの書き方、switchの書き方
Array、Dictionaryとかそのレベルの話。
超基礎 変数定義
いろんな言語巡りすぎて、Dim?var?いらない?型宣言いるっけ?頭だっけ?ってなる。IntだっけIntegerだっけってなるから書いておく
test.swift
//変数の宣言
let aaa:Int; // 変数は最初の一回のみ
var bbb:Int; // 変更がある場合はvarで定義
超基礎 if文
if文は比較的素直なきがする。
test.swift
if(int_value < 0 ){
print("Error")
return;
}
if int_value > 100 { // ifの後の括弧をつける場合はスペース必須
print("hello")
return;
}
超基礎 for文
for文は忘れる候補no1!
test.swift
let int_value:Int = 10;
for i:Int in 0..<int_value {
print("for文の書き方あれこれ",i)
}
// _は破棄変数。
// forEachを使う場合はループ変数を括弧の頭で "XX in"で受ける
// 省略する場合は、$0
// 処理内部で一度も$0を使用していない場合、_ inが必要
Array(0..<int_value).forEach {
_ in print("Array(0..<int_value).forEach")
}
//arrayの内容をindexとvalueで受けてループを回す
let array = ["a", "b", "c", "d"]
for (index, element) in array.enumerated() {
if (index % 2) != 0 {
print("\(index)つ目の要素:\(element)") // b, d
}else{
print("2で割り切れない場合非表示")
}
}
超基礎 switch
test.swift
switch int_value { // intでswitch
case 0:
print("0")
// breakいらない
case 1:
print("1")
fallthrough // 次のもcaseも実行したい時
default:
print("以外")
}
let doubleSwitch : [Double] = [1.5,2.0,3.0]
for (key,doubleAt) in doubleSwitch.enumerated(){
switch doubleAt {
case 0.0...2.0:
print("\(key) : \(doubleAt) :doubleでswitch")
case 2.0..<3.0:
print("\(key) : \(doubleAt) :doubleでswitch")
default:
print("else")
}
}
//switch でタプるも使えるよ
let a = (10,20)
switch a {
case(let first, let second) where first == 10 && second < 10:
print ("first 10 , second 10以下")
case(let first , let second ) where first == 10 && second == 20:
print ("first 10 , second 20 ")
default:
print("その他")
}
超基礎 array
test.swift
var sampleArray:[String] = ["a","b","c"]
print(sampleArray.capacity) // サイズ
print(sampleArray.startIndex) //初期値
print(sampleArray.endIndex) //最後
print(sampleArray.count) //個数
sampleArray.append("add1")
超基礎 Dictionary
test.swift
var sampleDict : Dictionary = ["test":"hogehoge", "test2":"hugahuga"]
sampleDict["add"] = "tuika"
//keysの一覧をArrayに取得
let keys: Array = Array(sampleDict.keys)
//valueの一覧をArrayに取得
let values: Array = Array(sampleDict.values)
// 例えばtest3があった時は表示、ない時は追加みたいな処理。
if let test3 = sampleDict["test3"]{
print("test3 is \(test3)") // test3がある時
}else{
sampleDict["test3"] = "naiyo"
}
ちょっと番外編 arrayの中身を弄り
よく配列のnilを除いたりしたい時にやり方忘れる。
test.swift
let array:[String?] = ["1","4",nil,"aaa","20"]
let testflat = testIn.flatMap{ $0 }
print(testflat)
print(testflat.flatMap{Int($0)})
let maxInt:Int = Int( testflat.flatMap{ Int($0)}.max()! )
let minString:String! = testflat.flatMap{ String($0) }.min()
print( maxInt ,"Int型")
print( minString, "String型")