Swift) collection types(and tuple)

2023. 9. 4. 00:11· Swift🐤
목차
  1. Array
  2. 형태
  3. 특징
  4. Set
  5. 형태
  6. 특징
  7. Dictionary
  8. Tuple
  9. 사용 목적
  10. 형태
  11. 특징
  12. Colltion types != Tuple

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

 

'Swift🐤' 카테고리의 다른 글

Swift) 열거형(enum)  (1) 2023.10.09
Swift) Nested Function  (0) 2023.09.06
Swift) Property Observers(프로퍼티 옵져버)  (0) 2023.09.04
Swift) ARC(Automatic Reference Counting)  (0) 2023.09.01
Swift) swift 일급객체  (0) 2023.07.13
  1. Array
  2. 형태
  3. 특징
  4. Set
  5. 형태
  6. 특징
  7. Dictionary
  8. Tuple
  9. 사용 목적
  10. 형태
  11. 특징
  12. Colltion types != Tuple
'Swift🐤' 카테고리의 다른 글
  • Swift) Nested Function
  • Swift) Property Observers(프로퍼티 옵져버)
  • Swift) ARC(Automatic Reference Counting)
  • Swift) swift 일급객체
성실농장주
성실농장주
매일 조금이라도 꾸준히 성장하고 싶은 개발자
성실농장주
사과농장
성실농장주
전체
오늘
어제
  • 분류 전체보기 (43)
    • iOS 개발공부📱 (4)
    • Swift🐤 (12)
    • SwiftUI🐧 (2)
    • Firebase 🔥 (1)
    • Git 🐈 (2)
    • Linux (1)
    • Trouble Shooting🛠️ (2)
    • 자료구조🏛️ (1)
    • visionOS 개발공부👓 (1)
    • Algorithm💡 (4)
    • RxSwift (5)
    • 오픈소스 (1)
    • ios 개발자 면접 질문🥸 (6)
    • 영어문서 단어집📕 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • responder_chain
  • RxSwift
  • Tuple
  • iOS_process_management
  • rethrows
  • CLLocationDegrees
  • Set
  • processor_management
  • Array
  • process_states
  • EnvironmentValues
  • process_control_block
  • Xcode
  • colorScheme
  • optional_chaining
  • control_transfer_statement
  • SWIFT
  • Debug View Hierarchy
  • git
  • nested_function

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.0
성실농장주
Swift) collection types(and tuple)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.