Written by
Amy
on
on
Swift String API
Swift String 다시보기
String
- Swift4이후 String은 Character의 Collection이 되었다.
- Swift String Cheatsheet
String은 Value 타입
var aString = "Hello"
var bString = aString
bString += " World!" // "Hello World!"
print("\(aString)") // "Hello\n"
repeating으로 같은 문자 반복
let hello = String(repeating:"hi", count:3) // hihihi
빈문자열
let name = ""
name.isEmpty // true
let name = String()
name.isEmpty // true
대소문자
let stringSample = "abcDEf"
let upper = mixedCase.uppercased() // "ABCDEF"
let lower = mixedCase.lowercased() // "abcdef"
Index
let hello = "hello"
let startIndex = hello.startIndex // 0
let endIndex = hello.endIndex // 5 (range 밖)
hello[hello.index(after: startIndex)] // "e"
hello[hello.index(before: endIndex)] // "o"
hello[hello.index(startIndex, offsetBy: 1)] // "e"
hello[hello.index(endIndex, offsetBy: -4)] // "e"
Attributed String
let font = UIFont(name: "HelveticaNeue-Light", size:20.0)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8
paragraphStyle.alignment = .center
textLabel.attributedText = NSAttributedString(string: text,
attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.paragraphStyle: paragraphStyle])
String을 Data로 Encoding/Decoding할 때 주의할 점
- String to Data and Back
- force-unwrapping은 위험하다. 기본적으로 리턴 타입은 Optional
URL, String
String(contentsOF:, encoding:)
String.split(seperator:)
URL.appendingPathComponent.path
let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Some Path")
let str = try! String(contentsOf: url, encoding: .ascii)
let lines = str.split(separator: "\n")