getting started Swift

X-codeのplaygroundでコードと実行結果を表示します。

//print("hello world")
print("hello world")

変数

//var msg: String
//msg = "hello world"
//変更ができない変数 let

//var msg = "hello world"

var msg = "hello"
let s = "hoge"
//s = "bar"
println("msg: \(msg), s: \(s)")

データ型

// String, Int, Float/Double, Bool, nil
// + - * / %
let x: Float = 8.0 % 2.5
var y = 0
y++
y

let s = "hello " + "world"
true && true
true || false
!true

let a = "hkt"
let b = 48
let c = a + String(b)

タプル: _xxx はxxxを破棄

//let error = (40, "not found")
//error.0
//error.1

let error = (code:40, msg:"not found")
error.code
error.msg

let error = (40, "not found")
//let (code, msg) = error
let (code, _msg) = error
code
msg

swift

var colors: [String] = ["blue", "pink"]
colors[0]
colors[1] = "red"
colors

colors.count
colors.isEmpty

colors.append("green")
colors.insert("gray", atIndex: 1)

let secondColor = colors.removeAtIndex(1)

dictionary

var users: [String: Int] = [
  "yamada": 500,
    "tanaka" : 800
]

users["yamada"]

users.count
users.isEmpty

users["ito"] = 900
users

users.removeValueForKey("ito")
users

users.updateValue(1000, forKey: "tanaka")
let keys = Array(users.keys)
let values = Array(users.values)

var emptyDictionary = [String: Int]()

if

let score = 72
var result = ""

if score > 80 {
    result = "Great"
} else if score > 60 {
   result = "good"
} else {
    result = "soso..."
}

result = score > 80 ? "great" : "so so..."

switch

let num = 7

switch num {
case 0:
    println("zero")
case 1, 2, 3:
    println("small")
case 4...6:
    println("4/5/6")
case 7..<9:
    println("7/8")
case let n where n > 10:
    println("huge")
default:
    println("n.a.")
}

while

var n = 0
//while n < 10 { // println(n) // n++ //} do { println(n) n++ } while n < 10 [/code] for

for var i = 0; i < 10; i++ {
 println(i)
}

for i in 0...9 {
    println(i)
}

let a = [5, 3, 10]
for i in a {
    println(i)
}