String

김태현·2022년 2월 18일
0

swift

목록 보기
1/7
post-thumbnail

language guide

Strings and Characters - The Swift Programming Language (Swift 5.6)


  • NSString

    [Bridging Between String and NSString](https://developer.apple.com/documentation/swift/string#2919514)
    
    > Any `String`instance can be bridged to `NSString` using the type-cast operator (`as`)
    > 
    
    > if you import Foundation, you can access those `NSString` methods on `String` without casting.
    > 

String Literals

: characters surrounded by double quotation marks (")

let someString = "Some string literal value"
let quotation = """
The White Rabbit put on his spectacles.  "Where shall I begin,
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""

  • line break(줄바꿈) 원하지 않을 때 : \
let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

  • Indentation

  • 특수문자
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024
let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496
let threeDoubleQuotationMarks = """
Escaping the first quotation mark \"""
Escaping all three quotation marks \"\"\"
"""

  • Strign delimiter

    #"Line 1\nLine 2"# : 줄바꿈 대신에 \n 출력됨

    #"Line 1\#nLine 2"# : 줄 바꿈 허용


Initializing an Empty String

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
// these two strings are both empty, and are equivalent to each other

String Mutability

var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"

let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified

Strings Are Value Types

String 절달(pass)이나 할당(assign) 시 복사본 전달

장점:

값 자체에 집중 (이유: 어디서 온 복사본인지 알 필요X) = 외부에서 변경될 걱정X(직접 수정만 가능)

compiler 최적화 → 실제 복사는 꼭 필요할 때 발생 → 성능 향상

Working with Characters

for character in "Dog!🐶" {
    print(character)
}
// D
// o
// g
// !
// 🐶
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"

Concatenating Strings and Characters

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// Prints two lines:
// one
// twothree

let goodStart = """
one
two

"""
print(goodStart + end)
// Prints three lines:
// one
// two
// three

String Interpolation

문자열에 변수 표현 \()

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
print(#"Write an interpolated string in Swift using \(multiplier)."#)
// Prints "Write an interpolated string in Swift using \(multiplier)."
print(#"6 times 7 is \#(6 * 7)."#)
// Prints "6 times 7 is 42."

Unicode

: text 인코딩 방식

  • unicode scalar value

A Unicode scalar value is a unique 21-bit number for a character or modifier, such as U+0061 for LATIN SMALL LETTER A ("a"), or U+1F425 for FRONT-FACING BABY CHICK ("🐥")

  • Extended Grapheme Clusters

Counting Characters

.count

Accessing and Modifying a String

let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a

  • 런타임 에러 발생 가능
greeting[greeting.endIndex] // Error
greeting.index(after: greeting.endIndex) // Error
  • indices
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n   T a g ! "
  • insert
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"

welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
  • remove
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
profile
iOS 공부 중

0개의 댓글