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)
}

View Controller Scene

screen-shot-2016-11-25-at-10-06-33

developer向けサイト:https://developer.apple.com
developerプログラム:https://developer.apple.com/programs/jp/

ctrl で、support editorにひも付けて、変数myLableにchnageLabelしています。


    @IBOutlet weak var myLabel: UILabel!

    @IBAction func changeLabel(sender: AnyObject) {
        myLabel.text = "You changed me"
    }

tips
command + 0 ->navigator area削除
auto size, auto layout on
story board -> assistant editor -> preview
upgrade frames ->制約に自動調整, items new constrainsで作成時につけることも可能
clear constrains ->制約を解除

上下左右幅いっぱいにするには margin 0
screen-shot-2016-11-25-at-11-15-42
constrain: Editor -> pin -> height or width
view ctrl + dragでも可能
viewを2つ選択して equal height
multiplier: 2つのviewの比率を設定
screen-shot-2016-11-25-at-11-28-09

labelなどのtextはxcode側でサイズを自動計算するので、必ずしも指定しなくてOK
content Hugging priority 大きくなりにくさ

deviceごとに表示を変えるには、画面下のsize classで設定