components์ split ๋ฉ์๋ ๋น๊ต / ๋ฌธ์์ด์ ํน์ ๋ฌธ์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฐฐ์ด๋ก ๋ณํ
์ฝ๋ฉํ ์คํธ ๋ฌธ์ ๋ฅผ ํ๋ค ๋ณด๋ฉด ์์ฃผ ์ฌ์ฉํ๋ ๋ฉ์๋๋ค์ด์ง๋ง
๋น์ทํ ๊ธฐ๋ฅ ๋๋ฌธ์ธ์ง ๋งค๋ฒ ํท๊ฐ๋ฆฌ๊ณค ํ๋ค.
์ด์ฐธ์ ์ ๋๋ก ์ ๋ฆฌ๋ฅผ ํด๋ณด๊ณ ์ ํ๋ค.
components(separatedBy:) ๋ฉ์๋์ split ๋ฉ์๋๋
๋ฌธ์์ด์ ํน์ ๊ตฌ๋ถ์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ถ๋ฆฌํ์ฌ ๋ฐฐ์ด๋ก ๋ฐํํ๋ค.
Swift์ String ํ์ ์ ์ ์๋ ๋ฉ์๋
let text = "one,two;three four"
let componentsResult = text.components(separatedBy: [",", ";", " "])
print(componentsResult) // ["one", "two", "three", "four"]
let text = "apple,banana,orange"
let fruits = text.components(separatedBy: ",") // [String] ํ์
print(fruits) //์ถ๋ ฅ: ["apple", "banana", "orange"]
let text = "one,,two"
let parts = text.components(separatedBy: ",")
print(parts) // ["one", "", "two"]
let text = "one,two,three"
let parts = text.split(separator: ",")
print(parts) // ["one", "two", "three"]
for part in parts {
print(part) // ๊ฐ๊ฐ์ ์์๋ Substring
}
// Substring์ String์ผ๋ก ๋ณํ
let strParts = parts.map { String($0) }
print(strParts) // ["one", "two", "three"]
let text = "one,,two"
let parts = text.split(separator: ",", omittingEmptySubsequences: false)
print(parts) // ["one", "", "two"]
let partsEmpty = text.split(separator: ",", omittingEmptySubsequences: true)
print(partsEmpty) // ["one", "two"]
[ Swift ] CRUD์ CoreData ํ๋ ์์ํฌ (0) | 2024.07.14 |
---|---|
[ Swift ] ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ(ARC) (0) | 2024.07.13 |
[ Swift ๊ธฐ์ด ๋ฌธ๋ฒ ] ๊ณ ์ฐจํจ์ - map, filter, reduce, forEach, compactMap, flatMap (0) | 2024.06.26 |
[ Swift ๊ธฐ์ด ๋ฌธ๋ฒ ] ํด๋ก์ (Closure) (0) | 2024.06.25 |
[ Swift ๊ธฐ์ด ๋ฌธ๋ฒ ] ํ๋กํ ์ฝ (Protocol) (0) | 2024.06.25 |