• Home
  • About
    • Lim Gun Woo photo

      Lim Gun Woo

      slowly, clamly

    • Learn More
    • Email
    • Facebook
    • Instagram
    • Github
    • Steam
  • Posts
    • All Posts
    • All Tags
  • Projects

[Siwft] - 3 - swift basic 문법 2

08 Sep 2018

Reading time ~3 minutes

Swift 기초 문법 2

1. Conditional Statements ( 조건문 )

If문

  • if문 형식

      if 조건 A {
          코드 // 조건 A 가 참일 때 실행
      }
      else if 조건 B { // 조건 A 가 거 짓일 때 조건 B 확인
          코드 // 조건 B 가 참일 때 실행
      }
      else { 
          코드 // 위 조건들이 거짓일 때 실행
      }
    
    • if문 에서는 “ , “ 는 AND 랑 의미가 동일
  • if 문의 중첩

  	if 조건 A {
		if 조건 a {
			코드
		}
	}

switch문

  • 여러 개의 조건 비교에 if~else if 구문 보다 효율적
  • switch문 형식
      switch index{
      case index1:
          index1 에 관한 코드
      case index2:
          index2 에 관한 코드
      case index3:
          index3 에 관한 코드
      default:
          default 에 관한 코드
      }
    
  • switch index 타입
    • character 타입도 사용 가능
      let alphabet: Character = "a
      switch  alphabet {
      case  "a":
        print("The first letter of the alphabet")
      case  "z":
       	print("The last letter of the alphabet")
      default: // Invalid, the case has an empty body
        break//  print("Some other character")
      }
      
    • Interval Matching (숫자 범위로 case 문 조건)
      let approximateCount = 30
      
      switch  approximateCount {
      case 0...50:
          print("0 ~ 50")
      case  51...100:
      	print("51 ~ 100")
      default:
      	print("Something else")
      }
      
    • Compound Cases
      case "a", "e", "c"
      
      • switch 에서는 “ , “ 는 OR 을 뜻한다
    • Value binding
       let stillAnotherPoint = (9, 0)
      
      switch  stillAnotherPoint {
      case (let distance, 0), (0, let distance): 
          print("On an axis, \(distance) from the origin")
      default:
          print("Not on an axis")
      }
      
      • 변수명으로 변수 값을 대신함으로 써 변수명을 사용한 자리는 신경쓰지 않겠다는 것을 의미
    • no default case
      let isTure:true
      
      switch isTure{
      case true:
      	print("t")
      case false:
          print("f")  
      }
      
      • ture or false 는 값이 둘중 하나 이므로 default 를 사용하면 error 가 난다
    • fallthrough -swift의 switch문은 break가 생략되어있어 break 기능을 사용하고 싶지 않을 때 사용
      switch index{
      case 1:
      	print("1")
      	fallthrough
      default:
          print("2")
      }
      

guard문

  • guard문 형식

      func update(age:Int){
          guard 0...100 ~= age, age == 100
          else {
              return
          }
          print("Pass")
      }
    
    • if문 코드의 간결화
    • if문과 다른 점은 조건의 결과가 참일 때 실행되는 코드가 없음

2. Loops ( 반복문 )

for 문

  • 횟수에 의한 반복
  • for 문 기본 형식
    for i in 0...10{ // i가 0부터 10까지 아래 code 를 반복
      code
    }
    
  • 문자열 for 문
  • 문자열로도 반복이 가능
  • 문자열의 크기만큼 반복함
      var word = "apple"
      for char in word.characters{
      	print(char) // a p p l e 총 5번 반복함
      }
    
  • 반복 상수의 생략 for 문
  • 반복 상수가 필요하지 않고 반복하는 것이 목적인 경우에 _ 를 사용하여 상수를 생략할 수 있음
      var num = 0
      for _ in 0...5{
      	num = num + 1
      }
    

while 문

  • 조건에 의한 반복
  • 실행 횟수가 명확하지 않은 경우에 사용
//ex
var i = 0
while i < 10 {
	i = i + 1
}
print(i)
  • 무한 while 문
while true {

}

repeat~while 문

  • while 문과 달리 코드를 먼저 실행한 후 조건을 평가하여 반복 여부를 결정
  • 반복 코드를 최소 한번은 수행함
var i = 0
repeat {
 i = i + 1
 }
 while i < 10
 
 print(i)

3. 제어 전달문

  • 코드의 조건문을 제어하거나 종료시킬 수 있음
  • 반복문이나 조건문, 함수 등에서 사용됨

break

  • switch 에서는 switch 구문의 실행을 종료하는 역할
  • 반복문에서는 반복문 전체 실행을 즉시 종료하고 반복문을 빠져나가 다음 코드를 실행함
	for row in 0...5{
		if row == 3 {
			break
		}
		print("this row is /(row)")
	}

continue

  • continue 는 아래의 코드를 건너뛰고 다음 반복을 시작시키는 역할
  • break 는 구문의 반복을 완전히 종료하지만 continue 는 조건에 따라 다음 반복을 실행함
	for row in 0...5 {
		if row < 3 {
			continue
		}
		print("this row is /(row)")
	}


swiftplayground Share Tweet +1