swift적응기_#2

woori·2023년 1월 30일
0

swift_study

목록 보기
2/2

swift 에서 사용하는 type에 관련된 내용, 나는 c/c++ 에 익숙하기 때문에 c++에 치환해서 생각하는게 더 쉽긴하다

  1. tuple
    python자료구조에서 보던 tuple인데, swift 에서의 튜플은 구조체와 유사한 개념이다.
var person:(String, Int, Double) = ("woori", 70, 176.4)

// index를 통해 값을 가져올 수 있다
print("name : \(person.0), age:\(person.1), height:\(person.2)

//index로 값을 할당할 수도 있다.
person.1 = 25
person.2 = 160.3

튜플 인덱스가 맞지않는 값을 할당할 때에는 에러가 반환될것..repl로 테스트

  6> var person:(String,Int,Double) = ("woori", 50, 32.1);
person: (String, Int, Double) = {
  0 = "woori"
  1 = 50
  2 = 32.100000000000001
}
  7> person.1 = 51.5
expression failed to parse:
error: repl.swift:7:12: error: cannot assign value of type 'Double' to type 'Int'
person.1 = 51.5
           ^~~~
           Int()

튜플 요소에 이름을 지정해 의미있게 사용할 수 있다.

var person:(name:String, age:Int, height:Double) = ("woori", 28, 170)

print(person.name);

같은모양의 튜플을 여러번 사용하고 싶은 경우, 튜플이 길어지면 쓰기 귀찮으므로, typealias 를 이용해 type 을 더 깔끔하게 쓸수 있다.

typealias PersonTuple = (name:String, age:Int, height:Double);

var eric:PersonTuple = ("eric", 42, 164.4); 
profile
기록하는개발자

0개의 댓글