iOS

[Swift] Ascii Code로 변환하기

hio9_9 2022. 12. 28. 16:01

c, c++에서는 char 타입이 1 byte 정수인 아스키코드로 저장되어서 char 타입에서 int로 형변환하여 쉽게 아스키코드 값을 구할 수 있다.

swift에서는 Character 타입은 단일 문자 string 으로 되어 있기 때문에 아스키코드 값을 구하기 위해서는 추가적인 변환이 필요하다.

 

asciiValue

var asciiValue: UInt8? { get }
// The ASCII encoding value of this character, if it is an ASCII character.
  • Charater 타입 문자의 아스키코드 값을 알 수 있다
  • 해당 문자의 아스키코드 값을 8UInt?로 반환한다
  • 사용 시에는 옵셔널을 벗겨 Int 타입으로 변환해 사용할 수 있다
let chars: [Character] = ["a", " ", "™"]
for ch in chars {
    print(ch, "-->", ch.asciiValue)
}
// Prints:
// a --> Optional(97)
//   --> Optional(32)
// ™ --> nil

 


unicodeScalars

var unicodeScalars: String.UnicodeScalarView { get set }
// The string’s value represented as a collection of Unicode scalar values.
@frozen struct UnicodeScalarView
// String.UnicodeScalarView
// A view of a string's contents as a collection of Unicode scalar values
  • UnicodeScalarView는 문자열의 Unicode value를 보여준다
  • 해당 문자의 유니코드 값을 UInt32로 반환한다
  • unicodeScalar property를 이용해 UnicodeScalarView를 사용할 수 있다
let flowers = "Flowers 💐"
for v in flowers.unicodeScalars {
    print(v.value)
}

// Prints: 
// 70
// 108
// 111
// 119
// 101
// 114
// 115
// 32
// 128144

 

(+) Character.unicodeScalars 사용하기

var unicodeScalars: Character.UnicodeScalarView { get }

// Character.UnicodeScalarView
typealias UnicodeScalarView = String.UnicodeScalarView

// using Character.UnicodeScalarView & Character.unicodeScalars
for c int flowers {
	let u = c.unicodeScalars.first!.value
    print(u)
}

 


urf16

var utf16: String.UTF16View { get set }
// A UTF-16 encoding of self.
@frozen struct UTF16View
// String.UTF16View
// A view of a string’s contents as a collection of UTF-16 code units.
  • UTF16 view는 문자열의 unicode scalar value를 UInt16으로 인코딩해 반환한다
  • UTF16 view는 utf16 property를 통해 접근할 수 있다
let flowers = "Flowers 💐"
for v in flowers.utf16 {
    print(v)
}
// 70
// 108
// 111
// 119
// 101
// 114
// 115
// 32
// 55357
// 56464
  • UnicodeScalarView는 21 bit인 반면에 UTF16View는 16 bit이다
  • 위 예시와 같은 이모지를 변환시키기 위해서는 2개의 UTR16View가 필요하다 (surrogate pairs)

 


UnicodeScalar

typealias UnicodeScalar = Unicode.Scalar
@frozen struct Scalar
// Unicode.Scalar
// A Unicode scalar value.
  • Unicode.Scalar type은 single Unicode scalar value이다
  • UnicodeScalar를 이용해 단일 문자로 이루어진 String의 유니코드 값을 구할 수 있다
let letterK: Unicode.Scalar = "K"
let kim: Unicode.Scalar = "김"
print(letterK, kim)
// Prints "K 김"
  • UnicodeScalar를 이용해 주어진 유니코드 값에 해당하는 문자를 구할 수 있다. (유니코드/아스키코드 → Character)
let airplane = Unicode.Scalar(9992)!
print(airplane)
// Prints "✈︎"

 


Example Code

let str = "hio"

print("Test 1 : asciiValue \n")
for c in str {
    let a = c.asciiValue!
  
    print("\(a) is \(type(of: a))")
    print("\(a) -> \(UnicodeScalar(a)) -> \(type(of: UnicodeScalar(a)))")
}
// Test 1 : asciiValue 

// 104 is UInt8
// 104 -> h -> Scalar
// 105 is UInt8
// 105 -> i -> Scalar
// 111 is UInt8
// 111 -> o -> Scalar


print("\n-------------------------\n")
print("Test 2 : unicodeScalars\n")

for c in str.unicodeScalars {
    print("\(c.value) is \(type(of: c.value))")
    print("\(c.value) -> \(UnicodeScalar(c.value)) -> \(type(of: UnicodeScalar(c.value)))")
}
print("\n---------OR---------\n")
for c in str {
  let u = c.unicodeScalars.first!.value
  
    print("\(u) is \(type(of: u))")
    print("\(u) -> \(UnicodeScalar(u)) -> \(type(of: UnicodeScalar(u)))")
}
// Test 2 : unicodeScalars

// 104 is UInt32
// 104 -> Optional("h") -> Optional<Scalar>
// 105 is UInt32
// 105 -> Optional("i") -> Optional<Scalar>
// 111 is UInt32
// 111 -> Optional("o") -> Optional<Scalar>

// ---------OR---------

// 104 is UInt32
// 104 -> Optional("h") -> Optional<Scalar>
// 105 is UInt32
// 105 -> Optional("i") -> Optional<Scalar>
// 111 is UInt32
// 111 -> Optional("o") -> Optional<Scalar>

 
print("\n-------------------------\n")
print("Test 3 : utf16\n")
 
for c in str.utf16 {
    print("\(c) is \(type(of: c))")
    print("\(c) -> \(UnicodeScalar(c)) -> \(type(of: UnicodeScalar(c)))")
}
// Test 3 : utf16

// 104 is UInt16
// 104 -> Optional("h") -> Optional<Scalar>
// 105 is UInt16
// 105 -> Optional("i") -> Optional<Scalar>
// 111 is UInt16
//111 -> Optional("o") -> Optional<Scalar>
 
 
print("\n-------------------------\n")
print("Test 4 : UnicodeScalar() \n")
 
for c in str {
    let u = (UnicodeScalar(String(c))!.value)
  
    print("\(u) is \(type(of: u))")
    print("\(u) -> \(UnicodeScalar(u)) -> \(type(of: UnicodeScalar(u)))")
}
// Test 4 : UnicodeScalar() 

// 104 is UInt32
// 104 -> Optional("h") -> Optional<Scalar>
// 105 is UInt32
// 105 -> Optional("i") -> Optional<Scalar>
// 111 is UInt32
// 111 -> Optional("o") -> Optional<Scalar>