Skip to content

Instantly share code, notes, and snippets.

@s-kiriki
Created December 2, 2014 04:53
Show Gist options
  • Save s-kiriki/98aec175f3490aa0c958 to your computer and use it in GitHub Desktop.
Save s-kiriki/98aec175f3490aa0c958 to your computer and use it in GitHub Desktop.
Swift勉強会#2
// Playground - noun: a place where people can play
import UIKit
//Optional型
//Optionalとはnilの代入を許すこと
//Optionalにするには?をつけてwrapする。
var a : Int = 3
var b : Int? = 2
var c : Int? = 20
//a = nil//これはエラーになる
b = nil//これはOK
//Optional型を使うときは!をつけてunwrapする
a+30
//c+20//これはエラー
c!+20//これはOK
//なんでもOKなAny型というものもある
//AnyはOptional
var x: Any = "hoge"
var y: Any = 30
//Any型を実際に使うときは型変換してからやる
// 型変換
var i = x as? Int//ダウンキャストできないのでnil
i = y as? Int
// for文
for var i=10; i<=20; i++ {
if i%7 == 0 {
println ("\(i) can be divided by 7")
}
}
var fruits_color : Dictionary = [
"apple" : "red",
"grape" : "purple",
"banana" : "yellow"
]
for (name, color) in fruits_color {
println ("\(name) は \(color)")
}
//switch文
var sw_number: Int = 1
switch(sw_number){
case 0...9://0~9
println("1桁")
case 10..<100://100は含まない
println("2桁")
default:
println("その他")
}
//関数
func calcSum(minNum:Int, maxNum:Int) -> Int {
var sum : Int = 0
for number in minNum...maxNum {
sum += number
}
return sum
}
calcSum(2,5)
//演習問題1
//引数にmax(Int)を指定し、1からmaxまでの2の倍数の合計値を返すメソッドを作る
func practice_1(max:Int) -> Int {
var sum = 0
for number in 1...max {
if(number%2 == 0) {
sum += number
}
}
return sum
}
practice_1(30)//240
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment