본문 바로가기
iOS/Swift

[Swift] 번호 기호(#)로 Raw String 사용하기

by Dev.Andy 2023. 7. 23.

머리말

참고 자료

Extended String Delimiters - Strings and Characters | Documentation

이스케이프 문자를 문자열로 표현하기 위한 번거로움

해당 문자 자체에 지정된 뜻을 가져서 곧바로 표현이 되지 않는 이스케이프 문자를 표현하기 위해서는 아래와 같이 문자의 바로 왼쪽에 역슬래시(\) 문자를 입력해야 한다.

let backslash = "\\\\" // 역슬래시
let lineFeed = "\\\\n" // 줄바꿈 문자(\\n)
let carriageReturn = "\\\\r" // 캐리지리턴 문자(\\r)
let tab = "\\\\t" // 탭 문자(\\t)
let quotationMark = "\\"" // " 큰따옴표 문자

하지만 하나의 문자열 안에 여러 개의 이스케이프 문자를 입력해야 한다면 어떻게 해야 할까? 그 사이에 매번 역슬래시(\) 문자를 입력하는 번거로움이 생길 것이다.

let exampleString = "there are special characters called escape characters like \\"\\\\r\\" and \\"\\\\n\\", \\"\\\\\\""
print(exampleString) // there are special characters called escape charaters like "\\r" and "\\n", "\\"

Swift의 Raw String

사용 방법과 특징

  • 이러한 불편함을 해소하기 위해 Swift에서는 번호 기호(#; number signs)를 문자열 기호(") 바깥에 한번 더 감싼 Raw String이 있다.
  • 이를 이용하면 손쉽게 이스케이프 문자를 표현할 수 있다.
  • 다만, 이스케이프 문자의 용도를 표현하고 싶다면 반대로 원래의 이스케이프 문자의 사이에 번호 기호를 입력하면 된다.
  • 문자열 보간법(String Interpolation)에도 적용이 되는데, 역슬래시와 소괄호 사이에 번호 기호를 입력하면 된다.
  • 번호 기호의 개수는 상관 없지만, 양쪽 끝에 넣을 개수와 이스케이프 문자 사이에 넣을 개수를 모두 통일시켜야 한다.
  • 여러 줄 문자열(multi-line string)에도 지원이 된다.

예시 코드

let rawString = #"I can freely write escape characters as string \n \t \b"#
// I can freely write escape characters as string \n \t \b

let rawString2 = #"Use \#n as a newline character"#
// Use 
//  as a newline character

let rawString3 = ##"Put the same number of # in both ends of the string"##
// Put the same number of # in both ends of the string

let word = "INTERPOLATED"
let rawString4 = #"I can interpolate variables like \#(word)."#
// I can interpolate variables like INTERPOLATED.

let rawString5 = ##"Use \##n as a newline character"##
// Use 
//  as a newline character

let multilineRawString = #"""
I can do anything like \ \n \t \v ...
as much as I want \\
"""#
// I can do anything like \ \n \t \v ...
// as much as I want \\

 

댓글