Swift🐤

Swift) collection types(and tuple)

성실농장주 2023. 9. 4. 00:11

Array

형태

var labotaryStudent: [String] = [yonghoon, dongju, woojae]

특징

  • 순서가 있음 (index)
  • 값의 중복 허용
  • 모든 값들은 같은 형태를 갖는다.

Set

형태

 

특징

  • 순서가 없음
  • 값의 중복 허용 X (모든 값들은 고유하다.)
  • 모든 값들은 같은 형태를 갖는다.

Dictionary

 

Tuple

사용 목적

주로 함수호출에서 한개 이상의 서로 다른 타입의 값들을 반환을 하려고 할때 사용이 됩니다.

/*
Int형태의 리스트를 입력 받았을때 그 중 최대값, 최소값, 값들을 모두 합한 값, 평균값을 튜플 형태로 반환하는 함수 입니다.
*/
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int, average: Double) {
    var minScore = scores[0]
    var maxScore = scores[0]
    var scoreSum = 0
    
    //모든 값들을 순회하게 하는 반복문
    for score in scores {
    	//가장 작은 값을 minScore변수에 저장
        if score < minScore {
            minScore = score
        }
        //가장 큰 값을 maxScore변수에 저장
        if score > maxScore {
            maxScore = score
        }
        //모든 값들을 scoreSum변수에 저장
        scoreSum += score
    }
    
    let averageScore = Double(scoreSum) / Double(scores.count)
    
    return (minScore, maxScore, scoreSum, averageScore)
}

let testScores = [90, 88, 75, 92, 84]
let statistics = calculateStatistics(scores: testScores)

print("Minimum Score: \(statistics.min)")
print("Maximum Score: \(statistics.max)")
print("Sum of Scores: \(statistics.sum)")
print("Average Score: \(statistics.average)")

 

형태

basic tuple

var student = ("dong_dong", 35, "Busan")

print(student.0) //dong_dong
print(student.1) //35
  • 소괄호'()'로 튜플을 정의
  • 서로 다른 타입으로 정의 가능(String, Int)
  • index로도 요소 값의 접근이 가능

Named tuple

var student = (name: dong_dong, age: 35, city: Busan)

//key값으로 value 접근 가능
print(student.name) //dong_dong
  • 요소에 이름을 붙이기 가능
  • Dictionary타입처럼 이름을 가지고 데이터 접속 가능 

Nested tuple

var nest = (1, "student", ("hi", "hello", 3))
//tuple안에 튜플이 가능
  • 튜플안에 튜플도 가능

 

특징

  • 튜플 생성하고 요소의 값 변경 X
  • tuple의 크기가 고정

 

Colltion types != Tuple

이유

  • tuple안에 다른 타입들(Int String, Double)이 섞일 수 있음
  • tuple은 한번 크기가 정해지면 크기 조정 X

 

reference: https://www.educative.io/answers/what-are-tuples-in-swift