[Swift 기초 문법] 데이터 타입 +@

Jonghun Kim·2023년 1월 11일
0

튜플

튜플(Tuple)은 지정된 데이터의 묶음이라고 표현할 수 있다.
다음 코드를 보면 더욱 이해가 더 빠를 것이다.
입력

var person: (String, Int, Double) = ("Geniewiz", 300, 173.3)

print("name: \(person.0), age: \(person.1), height: \(person.2)")

person.1 = 301
person.2 = 183.3

print("name: \(person.0), age: \(person.1), height: \(person.2)")

출력

name: Geniewiz, age: 300, height: 173.3
name: Geniewiz, age: 301, height: 183.3

컬렉션

스위프트는 튜플 외에도 많은 수의 데이터를 묶어 저장하고 관리할 수 있는 컬렉션 타입을 제공한다. 컬렉션 타입에는 배열, 딕셔너리, 세트 등이 있다.

배열

배열은 같은 타입의 데이터를 일렬로 나열한 후 순서대로 저장하는 형태의 컬렉션 타입이다.
배열을 사용할 때는 Array 키워드와 타입 이름의 조합으로 사용할 수 있다.
입력

var names: Array<String> = ["Geniewiz", "Coffee", "Mac"]

// 위 선언과 동일한 표현
//var names: [String] = ["Geniewiz", "Coffee, Mac"]

var emptyArray: [Any] = [Any]() //Any 데이터를 요소로 갖는 빈 배열 생성

//위 선언과 같은 동작을 하는 코드
//var emptyArray: [Any] = Array<Any>()

//배열의 타입을 잘 명시해 주었다면 []만으로도 빈 배열 생성 가능
//var emptyArray: [Any]=[]
print(emptyArray.isEmpty) //true
print(names.count) //3


print(names[2])
names[2] = "Macbook Air"
print(names[2])

names.append("Sweet Potato") // index:3
names.append(contentsOf: ["bakugo", "deku"]) // index:4,5
names.insert("Geniewiz2", at: 0) // Geniewiz is moved to index 1, and other elements is moved to (n+1) too
names.insert(contentsOf: ["Doctor K", "Jacob"], at: 4) // 

print(names[3])
print(names.firstIndex(of: "Geniewiz2"))
print(names.firstIndex(of: "Sonic"))
print(names.first)
print(names.last)

print(names[0 ... names.count-1])

let firstItem: String = names.removeFirst() //"Geniewiz2" is removed
let lastItem: String = names.removeLast() // "deku" is removed
let indexZeroItem: String = names.remove(at:0) // "Geniewiz" is removed

print(firstItem)
print(lastItem)
print(indexZeroItem)
print(names[0 ... 3])

print(names.count)
print(names)

출력

true
3
Mac
Macbook Air
Macbook Air
Optional(0)
nil
Optional("Geniewiz2")
Optional("deku")
["Geniewiz2", "Geniewiz", "Coffee", "Macbook Air", "Doctor K", "Jacob", "Sweet Potato", "bakugo", "deku"]
Geniewiz2
deku
Geniewiz
["Coffee", "Macbook Air", "Doctor K", "Jacob"]
6
["Coffee", "Macbook Air", "Doctor K", "Jacob", "Sweet Potato", "bakugo"]

딕셔너리

딕셔너리는 요소들이 순서 없이 키와 값 쌍으로 구성되는 구성 타입이다. 딕셔너리 저장되는 값은 항상 키와 쌍을 이루게 되는데, 딕셔너리 안에는 키가 하나이거나 여러 개일 수도 있다. 단, 하나의 딕셔너리 안의 키는 같은 이름을 중복해서 사용할 수 없다.

입력

typealias StringIntDictionary = [String: Int]

var numberForname: Dictionary<String, Int> = Dictionary<String, Int>()
//아래의 코드는 위의 코드와 같은 표현이다.
//  var numberForname: [String: Int] = [String: Int]()
//  var numberForname: StringIntDictionary = StringIntDictionary()

// 딕셔너리의 키와 값 타입을 정확히 명시해 주었다면 [:] 만으로도 빈 딕셔너리 생성가능
// var numberForname: [String: Int] = [:]

var numberForname1: StringIntDictionary = ["Geniewiz": 100, "Geniewiz2": 200, "Geniewiz3": 300]

print(numberForname1.count) // 3
print(numberForname1.isEmpty) //false
print(numberForname.isEmpty) // true

print(numberForname1["Geniewiz2"]) // 200
print(numberForname1["Geniewiz4"]) // nil

numberForname1["Geniewiz2"] = 150 // 200 -> 150
print(numberForname1["Geniewiz2"]) // 150

numberForname1["Trickster"] = 1
print(numberForname1["Trickster"]) // 1

print(numberForname1.removeValue(forKey: "Geniewiz"))
print(numberForname1["Geniewiz", default: 0]) // Geniewiz키에 해당 값이 없다면 0 반환




출력

3
false
true
Optional(200)
nil
Optional(150)
Optional(1)
Optional(100)
0

세트

세트는 같은 타입의 데이터를 순서 없이 하나의 묶음으로 저장하는 형태의 컬렉션 타입이다. 따라서 중복된 값이 존재하지 않는다. 그래서 세트는 보통 순서가 중요하지 않거나 각 요소가 유일한 값이어야 하는 경우에 사용한다. 또한, 세트의 요소로는 해시 가능한 값이 들어와야 한다.
세트는 Set 키워드와 타입 이름의 조합으로 써준다.

입력

var names: Set<String> = Set<String>()
var names1: Set<String> = ["Geniewiz", "Eclipse", "Ashtarte", "Hekate", "Blood Mage", "Swift Master", "Dimension Walker"]
var names2: Set<String> = ["Geniewiz", "Eclipse", "Ashtarte", "Hekate", "Geniewiz2"]


var numbers = [100, 200, 300]// 타입 추론시 컴파일러는 Set가 아닌 Array로 타입을 지정
print(type(of: numbers)) // Array<Int>

print(names2.isEmpty)    // false
print(names2.count)    //4
print(names.isEmpty)    // true

names2.insert("Archmage")
print(names2.count) // 5

print(names2.remove("Geniewiz2"))
print(names2.remove("Blood Mage")) // nil

// 집합연산
let mathClassStudents: Set<String> = names2
let englishClassStudents: Set<String> = names1

let intersectSet: Set<String> = englishClassStudents.intersection(mathClassStudents) // 교집합
let symmetricDiffSet: Set<String> = englishClassStudents.symmetricDifference(mathClassStudents) // 여집합의 합

let unionSet: Set<String> = englishClassStudents.union(mathClassStudents)// 합집합

let subtractSet: Set<String> = englishClassStudents.subtracting(mathClassStudents) // 차집합

print(unionSet)
print(unionSet.sorted())

//포함 관계 연산

let 새: Set<String> = ["비둘기", "닭", "기러기"]
let 포유류: Set<String> = ["사자", "호랑이", "곰"]
let 동물: Set<String> = 새.union(포유류)

print(새.isDisjoint(with: 포유류)) // 서로 배타적인가? -> true
print(새.isSubset(of: 동물)) // 새가 동물의 부분집한인가? -> true
print(동물.isSuperset(of: 포유류)) // 동물은 포유류의 전체를 포함하는가? -> true
print(동물.isSuperset(of: 새)) // 동물은 새의 전체를 포함하는가? -> true
print(새.isSuperset(of: 동물)) // 새는 동물의 전체를 포함하는가? -> false


출력

Array<Int>
false
5
true
6
Optional("Geniewiz2")
nil
["Ashtarte", "Swift Master", "Blood Mage", "Archmage", "Hekate", "Dimension Walker", "Geniewiz", "Eclipse"]
["Archmage", "Ashtarte", "Blood Mage", "Dimension Walker", "Eclipse", "Geniewiz", "Hekate", "Swift Master"]
true
true
true
true
false

열거형

열거형은 연관된 항목들을 묶어서 표현할 수 있는 타입이다. 열거형은 배열이나 딕셔너리 같은 타입과 다르게 프로그래머가 정의해준 항목 값 외에는 추가/수정이 불가능하다. 따라서 정해진 값만 열거형 값에 속할 수 있다.

기본 열거형

스위프트의 열거형은 enum이라는 키워드로 선언할 수 있다.
입력

enum School{
    case primary
    case elementary
    case middle
    case high
    case college
    case university
    case graduate
}

var highestEducationLevel: School = School.university
var highestEducationLevel1: School = .university // 위의 코드와 같은 동작을 하는 선언문

highestEducationLevel = .graduate

print(highestEducationLevel)
print(type(of: highestEducationLevel))

출력

graduate
School

원시값

열거형의 각 항목은 자체로도 하나의 값이지만 항목의 원시 값도 가질 수 있다. 즉, 특정 타입으로 지정된 값을 가질 수 있다는 뜻이다. 특정 타입 값을 원시 값으로 가지고 싶다면 열거형 이름 오른쪽에 타입을 명시해주면 된다. 또한, 원시 값을 사용하고 싶다면 rawValue 프로퍼티를 통해 가져올 수 있다.
입력

enum School: String{
    case primary = "유치원"
    case elementary = "초등학교"
    case middle = "중학교"
    case high = "고등학교"
    case college = "대학"
    case university = "대학교"
    case graduate = "대학원"
}

let highestEducationLevel: School = School.graduate
print("저의 최종학력은 \(highestEducationLevel.rawValue) 졸업입니다.")
print(type(of: highestEducationLevel))

enum WeekDays: Character {
    case mon = "월", tue = "화", wed = "수", thu = "목", fri = "금", sat = "토", sun = "일"
}

let today:WeekDays = WeekDays.fri
print("오늘은 \(today.rawValue) 입니다.")


// 열거형의 원시 값 일부 지정 및 자동 처리
enum School2: String{
    case primary = "유치원"
    case elementary = "초등학교"
    case middle = "중학교"
    case high = "고등학교"
    case college 
    case university
    case graduate
}
let highestEducationLevel2: School2 = School2.graduate
print("저의 최종학력은 \(highestEducationLevel2.rawValue) 졸업입니다.")
print(type(of: highestEducationLevel2))

enum Numbers: Int{
    case zero
    case one
    case two
    case ten = 10
}
print("\(Numbers.zero.rawValue), \(Numbers.one.rawValue), \(Numbers.two.rawValue), \(Numbers.ten.rawValue)")

출력

저의 최종학력은 대학원 졸업입니다.
School
오늘은 금 입니다.
저의 최종학력은 graduate 졸업입니다.
School2
0, 1, 2, 10

연관 값

스위프트의 열거형 각 항목이 연관 값을 가지게 되면, 기존 프로그래밍 언어의 공용체 형태를 띌 수도 있다. 열겨형 내의 항목(case)이 자신과 연관된 값을 가질 수 있다. 연관 값은 각 항목 옆에 소괄호로 묶어 표현할 수 있다.

enum MainDish{
    case pasta(taste: String)
    case pizza(dough: String, topping: String)
    case chicken(withSauce: Bool)
    case rice
}

var dinner: MainDish = MainDish.pasta(taste: "cream")
dinner = .pizza(dough: "thin dough", topping: "cheese")
dinner = .chicken(withSauce: true)
dinner = .rice

enum PastaTaste {
    case cream, tomato
}
enum PizzaDough {
    case cheeseCrust, thin, original
}
enum PizzaTopping{
    case pepperoni, cheese, bacon
}

enum MainDish2{
    case pasta(taste: PastaTaste)
    case pizza(dough: PizzaDough, topping: PizzaTopping)
    case chicken(withSauce: Bool)
    case rice
}

var dinner2: MainDish2 = MainDish2.pasta(taste: PastaTaste.tomato)
dinner2 = MainDish2.pizza(dough: PizzaDough.cheeseCrust, topping: PizzaTopping.bacon)
profile
likeCaffeine

0개의 댓글