String


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."
    """
  • 断線不要(改行)の場合:
  • 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月または割当時に복사본を転送
    メリット:
    値そのものに焦点を当てる(理由:コピーXがどこから来たのかを知る必要がある)=外部変更Xの心配(手動変更のみ)
    コンパイラ最適化→必要に応じて実際のレプリケーション→パフォーマンスの向上

    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


    :テキストエンコーディング方式
  • 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"