Swift 기초 문법 <11>

구찌댕댕이·2022년 7월 22일
0

swift 기초 문법

목록 보기
11/12
post-thumbnail

String

String은 구조체, NSString은 클래스 -> Bridging 가능하다.(서로 왔다 갔다 가능)
스위프트 자료형은 모두 구조체
Array, Dictionary 는 제네릭 구조체

String Literals : 한줄, 여러줄(개행 여부)

let helloStirng = "Hello, Swift!" //한줄 문자열

let alice = """
one
two
three
...
""" //여러줄 문자열(개행 포함 -> 다음줄로 넘어가지는것)

let wonderland = """
one \
two \
three
four
...
""" //여러줄 문자열, 이어서 출력하고 싶으면 \ 사용
print(helloStirng)
print(alice)
print(wonderland) // one two three 는 이어서 나오고 four는 다음 줄에 나온다.

특수문자 / 이스케이프 시퀀스

표준문자세트 뿐만 아니라 문자열에 개행, 탭, 또는 유니코드 값과 같은 항목을 지정할 수 있는 여러 특수 문자
특수 문자들은 역슬래시를 접두어로 하여 구별
var newline = "\n"
역슬래시로 시작되는 모든 문자는 특수 문자로 간주
역슬래시 문자 자체 : var backslash = "\"
일반적으로 많이 사용되는 특수 문자

  • \n - 개행
  • \r - 캐리지 리턴(carriage return)
  • \t - 수평 탭
  • \ - 역슬래시
  • \" - 큰따옴표
  • \' - 작은따옴표
  • \u{nn} - nn 위치에 유니코드 문자를 표현하는 두 개의 16진수가 배치되는 1바이트 유니코드 스칼라
  • \u{nnnn} - nnnn 위치에 유니코드 문자를 표현하는 네 개의 16진수가 배치되는 2바이트 유니코드 스칼라
  • \u{nnnnnnnn} - nnnnnnnn 위치에 유니코드 문자를 표현하는 네 개의 16진수가 배치되는 4바이트 유니코드 스칼라
let string1 = "\"hi\""
let dollar = "\u{24}"
let blackHeart = "\u{2665}"
let sparklingHeart = "\u{1F496}"
let ga = "\u{AC00}"
print(string1) //"hi"
print(dollar) //$
print(blackHeart) //♥
print(sparklingHeart) //💖
print(ga) //가
print("가") //가

빈 String 만들기

var emptyString = "" //empty string literal
var emptyString2 = String() //initializer 호출하여 빈 string 생성
if emptyString.isEmpty {
    print("빈 스트링") //공백이 있으면 빈 string이 아니게 된다.
}
if emptyString2.isEmpty {
    print("빈 스트링")
}

Character형 배열로 String형 만들기

let charCat: [Character] = ["C", "a", "t", "!"]
//let charCat = ["C", "a", "t", "!"] 으로 한다면 Array<String> 타입으로 나온다.
let stringCat = String(charCat)
print(stringCat)

for in

for character in "a bcd" {
    print(character)
} // 공백 포함 한줄씩 나온다

문자열 연결(Concatenating String)

let string1 = "Hello"
let string2 = " swift"
let exclamationMark: Character = "!"
var welcome = string1 + string2
print(welcome) // Hello swift
welcome.append(exclamationMark)
print(welcome) // Hello swift!
welcome.append("안녕")
print(welcome) // Hello swift!안녕

var hi = "Hi"
hi += string2
print(hi) // Hi swift

문자열 보간

let a = 3
let message = "\(a)에 3.5를 더하면 \(a + 3.5) 입니다."
// Int 와 Double끼리 연산 불가능 -> \(a + 3) 은 가능
let message2 = "\(a)에 3.5를 더하면 \(Double(a) + 3.5) 입니다."
// a 를 Double형으로 바꾼후 연산
print(message2)

Stirng 의 count 프로퍼티

var word = "Hello"
print(word) //Hello
print(word.count) //5
word += "안녕!"
print(word) //Hello안녕!
print(word.count) //8
word += "\u{1F496}"
print(word) //Hello안녕!💖
print(word.count) //9 -> 유니코드도 1개로 카운트

index 관련 프로퍼티와 메서드

let hi = "Hello 12345안녕"
print(hi.startIndex) //Index(_rawBits: 1)
print(hi.endIndex) //Index(_rawBits: 1114113) -> 제일 뒤 문자열 다음
print(type(of: hi.startIndex)) //Index

print(hi[hi.startIndex]) //H -> hi.[hi.endIndex] 는 값 없음
print(hi[hi.index(before:hi.endIndex)]) //녕
print(hi[hi.index(after: hi.startIndex)]) //e
var index = hi.index(hi.startIndex, offsetBy:7) // 뒤로 7번째
print(hi[index]) //2
index = hi.index(hi.endIndex, offsetBy: -1) // 앞으로 1번째
print(hi[index]) //녕
for i in hi.indices { // indices 는 index의 복수형
    print(hi[i], terminator: "")
}
//Hello 12345안녕

추가, 삭제

var hi = "hello"
hi.insert("!", at: hi.endIndex)
print(hi) //hello!
hi.insert(contentsOf: "54321", at: hi.index(before: hi.endIndex))
print(hi) //hello54321!
hi.remove(at: hi.index(before: hi.endIndex))
print(hi) //hello54321
let range = hi.index(hi.endIndex, offsetBy: -4)..<hi.endIndex
hi.removeSubrange(range)
print(hi) //hello5

Substring

let hi = "Hello, world!"
var index = hi.firstIndex(of: ",") ?? hi.endIndex // 값이 나오는게 확실하다면 ! 로 언래핑
print(hi[hi.firstIndex(of: ",") ?? hi.endIndex]) // ,
var x = hi[..<index] // , 전까지
print(x) //Hello
print(type(of: x)) //Substring
let newString = String(x)
print(newString) //Hello
print(type(of: newString)) //String
//예제 -> seoul만 String형으로 만들기
let jpg = "seoul.jpg"
var x = String(jpg[..<jpg.index(jpg.startIndex, offsetBy: 5)])
print(x)
print(type(of: x))
  • String에 특정 접두사가 있는지 여부 : hasPrefix
  • String에 특정 접미사기 있는지 여부 : hasSuffix
let x = "Chapter 1. Swift 기초"
print(x.hasPrefix("Chapter")) //true
print(x.hasSuffix("기초"))

let romeoAndJuliet = [
"Act 1 Scene 1 : ~~~a",
"Act 1 Scene 2 : ~~~b",
"Act 1 Scene 3 : ~~~c",
"Act 1 Scene 4 : ~~~a",
"Act 1 Scene 5 : ~~~b",
"Act 2 Scene 1 : ~~~c",
"Act 2 Scene 2 : ~~~a",
"Act 2 Scene 3 : ~~~b",
"Act 2 Scene 4 : ~~~c",
"Act 2 Scene 5 : ~~~a",
"Act 2 Scene 6 : ~~~b",
]
var act1SecneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SecneCount += 1
    }
}
print("There are \(act1SecneCount) scene in Act 1")

var aCount = 0
var cCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("a") {
        aCount += 1
    } else if scene.hasSuffix("c") {
                cCount += 1
    }
}
print("\(aCount) a scenes, \(cCount) c scenes")

유니코드

Character Set(문자셋) -> 문자의 집합, 문자 테이블
유니코드는 전세계의 모든 문자를 표현할 수 있는 단 하나의 문자셋
전세계의 문자에 특정 번호를 매겨 테이블로 만들어 둠
새로운 문자가 추가 된다면 새로운 번호를 매겨주면 된다 -> 이 번호를 코드포인트(code point)

  • 코드포인트 표기는 U+0041 과 같이 함
    U+는 유니코드를 의미하고, 0041은 코드포인트 값으로 16진수
    U+0041은 영어 알파벳 'A'
    U+AC00은 한글 '가'

유니코드 인코딩 : 유니코드 문자에 매겨진 정수 숫자(코드포인트)는 16진수 -> 2진수로 저장

  • 유니코드 변환 형식 인코딩(UTF)
  • 국제 문자 세트 인코딩(UCS)

UTF-32, UTF-16, UTF-8 등을 제공 (숫자는 최소 단위 바이트)
인코딩된 바이트 형태는 서로 다르지만 3가지 인코딩 모두 유니코드문자 전부를 표현할수 있으므로 인코딩 간 변환을 거쳐도 데이터 손실은 발생하지 않는다.

출처 : https://www.youtube.com/channel/UCM8wseo6DkA-D7yGlCrcrwA/playlists

profile
개발자를 꿈꾸는 사람 입니당

0개의 댓글