페이지

2020년 2월 9일 일요일

Swift loop, switch,fallthrough

//1. loop

for i in 0...3 {
    print(i)
}

for i in (0...3).reversed(){
    print(i)
}


//2. switch interval matching
let a = 32
switch a {
case 0,3:
    print("0,3")
case 0...19:
    print("...19")
case 20..<40:
    print("20..<40")
default:
    print("default")
}





// switch tuples

let a = (1, 1)
switch a {
case (0, 0):
    print("(0, 0) is at the origin")
case (_, 0):
    print("(\(a.0), 0) is on the x-axis")
case (0, _):
    print("(0, \(a.1)) is on the y-axis")
case (-2...2, -2...2):
    print("(\(a.0), \(a.1)) is inside the box")
default:
    print("(\(a.0), \(a.1)) is outside of the box")

}





// switch value binding

let a = (2, 0)
switch a {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
case (let x,0),(0, let x):       
    //warning: case will never be executed
    print("On an axis, \(x) from the origin")
case (let x,0),(0, let y) :      
    //error: x,y must be bound in every pattern
    print("error")

}





//switch where

let a = (101,10)
switch a {
case let(x,y) where x == y :
    print("x==y")
case let(x,y) where x >= y :
    print("x>=y")
case let(x,y) where x <= y :
    print("x<=y")
default:
    print("default")
}



// switch fallthrough

var a = 1
switch a {
    case 0...4:
        print("0...4")
        fallthrough
    case 5...10:
        print("5....10")
    case 11...14:
        print("11...14")
    default:
        print("default")
}




댓글 없음:

댓글 쓰기