String의 dropLast()와 removeLast()의 차이점 정리

4651 단어 Swifttech
Swift String에서 마지막 텍스트 삭제 작업
  • dropLast()
  • removeLast()
  • 거행할 수 있을 것 같습니다.이름이 비슷해 얼핏 보면 구별하기 어렵지만 내부에서는 전혀 다른 행동을 한다.
    만일을 대비해서 총결산을 하기로 했다.두 가지 방법의 문서에 따라 총결하다.

    dropLast(_:)


    Returns a subsequence containing all but the specified number of final elements.
    func dropLast(_ k: Int) -> Substring
    
    끝에서 제k개 원소를 제외한 부분의 집합을 반환값으로 되돌려줍니다.
    여기dropLast()에서는 객체 문자열에 지정된 꼬리 범위에서 제외된 나머지를 Substring 유형의 값으로 생성하고 반환합니다.따라서 대상 문자열(인스턴스)에서 값이 수정되지 않습니다.
    let str = "abcdef"
    
    print(str.dropLast()) // abcde
    print(str) // abcdef
    
    https://developer.apple.com/documentation/swift/string/2893517-droplast

    removeLast(_:)


    Removes and returns the last element of the collection.
    @discardableResult mutating func removeLast() -> Character
    
    collection의 마지막 요소를 배제하고 배제된 요소를 반환한다.(Removes 및 returns의 목적어는 항상 the last element)
    방법의 정의를 다시 한 번 봅시다.
  • 또는 반환값 @discardableResult
  • 을 사용하지 않을 수도 있음
  • 객체로서 인스턴스의 값 자체를 변경mutating
  • 알고 있습니다.반환값은 제외된 수치가 아니라 제외된 요소 자체라는 점과 객체 인스턴스 자체를 변경한 점dropLast()과 크게 다르다.
    var str2 = "abcdef" // mutating funcなので、letに対してremoveLast()は適用できない
    print(str2.removeLast()) // f
    print(str2) // abcde
    
    var str3 = "abcdef"
    str3.removeLast() // 返却値を演算に使わず、末尾要素の削除のみを行う
    print(str3) // abcde
    
    https://developer.apple.com/documentation/swift/string/2892866-removelast

    참고 자료


    https://developer.apple.com/documentation/swift/string

    좋은 웹페이지 즐겨찾기