String
✅ Array: An ordered, random-access collection.
Preinitialized with a fixed number of default values
var digitCounts = Array(repeating: 0, count: 10)
print(digitCounts)
// Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
Accessing Array Values
for in
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
for street in streets {
print("I don't live on \(street).")
}
// Prints "I don't live on Albemarle."
// Prints "I don't live on Brandywine."
// Prints "I don't live on Chesapeake."
.isEmpty .count
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
if oddNumbers.isEmpty {
print("I don't know any odd numbers.")
} else {
print("I know \(oddNumbers.count) odd numbers.")
}
// Prints "I know 8 odd numbers."
.first .last
if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last {
print(firstElement, lastElement, separator: ", ")
}
// Prints "1, 15"
var emptyDoubles: [Double] = []
print(emptyDoubles.first, emptyDoubles.last, separator: ", ")
// Prints "nil, nil"
Adding and Removing Elements
.append() .append(contentsOf: ) .insert(, at: )
.remove(at: ) .removeLast(),
.firstIndex(of: )
var students = ["Ben", "Ivy", "Jordell"]
students.append("Maxime")
students.append(contentsOf: ["Shakia", "William"])
// ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"]
students.insert("Liam", at: 3)
// ["Ben", "Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"]
students.remove(at: 0)
// ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"]
students.removeLast()
// ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"]
if let i = students.firstIndex(of: "Maxime") {
students[i] = "Max"
}
// ["Ivy", "Jordell", "Liam", "Max", "Shakia"]
✅ Set: An unordered collection of unique elements.
초기화
let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.contains("sugar") {
print("No thanks, too sweet.")
}
// Prints "No thanks, too sweet."
연산자
.contains(_:)
== .isSubset(of: ) .isSuperset(of: ) isStrictSubset(of:) isStrictSuperset(of:) isDisjoint(with:)
.union(_: ) .intersection(_: ) .symmetricDifference(_: ) .subtracting(:_ )
var primes: Set = [2, 3, 5, 7]
// Tests whether primes is a subset of a Range<Int>
print(primes.isSubset(of: 0..<10))
// Prints "true"
// Performs an intersection with an Array<Int>
let favoriteNumbers = [5, 7, 15, 21]
print(primes.intersection(favoriteNumbers))
// Prints "[5, 7]"
Sequence and Collection Operations
if primes.isEmpty {
print("No primes!")
} else {
print("We have \(primes.count) primes.")
}
// Prints "We have 4 primes."
let primesSum = primes.reduce(0, +)
// 'primesSum' == 17
let primeStrings = primes.sorted().map(String.init)
// 'primeStrings' == ["2", "3", "5", "7"]
for number in primes {
print(number)
}
// Prints "5"
// Prints "7"
// Prints "2"
// Prints "3"
let primesStrings = primes.map(String.init)
// 'primesStrings' is of type Array<String>
let primesStringsSet = Set(primes.map(String.init))
// 'primesStringsSet' is of type Set<String>
✅ Dictionary: A collection whose elements are key-value pairs.
초기화
var responseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
var emptyDict: [String: String] = [:]
Getting and Setting Dictionary Values
print(responseMessages[200])
// Prints "Optional("OK")"
let httpResponseCodes = [200, 403, 301]
for code in httpResponseCodes {
if let message = responseMessages[code] {
print("Response \(code): \(message)")
} else {
print("Unknown response \(code)")
}
}
// Prints "Response 200: OK"
// Prints "Response 403: Access forbidden"
// Prints "Unknown response 301"
추가, 삭제
Optional 값으로 나오는 것 주의
responseMessages[301] = "Moved permanently"
print(responseMessages[301])
// Prints "Optional("Moved permanently")"
삭제: nil 대입
responseMessages[404] = "Not found"
responseMessages[500] = nil
print(responseMessages)
// Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
Dictionary.keys
Dictionary[key]?
Dictionary[key]!
var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
"triangular": [1, 3, 6, 10, 15, 21, 28],
"hexagonal": [1, 6, 15, 28, 45, 66, 91]]
for key in interestingNumbers.keys {
interestingNumbers[key]?.sort(by: >)
}
print(interestingNumbers["primes"]!)
// Prints "[17, 13, 11, 7, 5, 3, 2]"
key, value 동시 접근
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
for (name, path) in imagePaths {
print("The path to '\(name)' is '\(path)'.")
}
// Prints "The path to 'star' is '/glyphs/star.png'."
// Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
// Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
.firstIndex(where: Closure)
.hasPrefix(_:)
let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
if let index = glyphIndex {
print("The '\(imagePaths[index].key)' image is a glyph.")
} else {
print("No glyphs found!")
}
// Prints "The 'star' image is a glyph.")
Closure, High Ordered Function
Reference
- https://developer.apple.com/documentation/swift/string
- https://developer.apple.com/documentation/swift/array
- https://developer.apple.com/documentation/swift/set
- https://developer.apple.com/documentation/swift/dictionary
- https://developer.apple.com/documentation/swift/range
'Development > Swift' 카테고리의 다른 글
[Swift] Higher Order Function / 고차함수 (0) | 2022.02.25 |
---|---|
[Swift] Closure (0) | 2022.02.17 |
[Swift] Extensions (0) | 2021.12.17 |
[Swift] Structures and Classes (0) | 2021.12.14 |
[Swift] Optional (0) | 2021.12.07 |