개발/아이오에스

기본 연산자 - 문자열과 문자

dev.jake 2020. 12. 1. 17:06
let b = 10
var a = 5
a = b  //a 값은 10

튜플사용 
let(x,y)=(1,2) //x=1 y=2

오브젝트c와 다르게 swift에서는 할당 연산자는 값을 반환하지 않습니다.
if x=y{
  //x=y는 값을 반환하지 않기 때문에 이 문법은 올바르지 않습니다.
}
할당 연산자가 값을 반환하지 않는 이유는 동등비교연산자(==)를 사용해야 하는 곳에 할당연산자(=)가 실수로 사용되는 것을 막기 위함

"hello, " + "world"  // equals "hello, world"
let three = 3
let minusThree = -three       // minusThree는 -3
let plusThree = -minusThree   // plusThree는 3, 혹은 "minus minus 3"

let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix는 -6

var a = 1
a += 2
// a는 3

Swift는 객체 비교를 위해 식별 연산자 === 과 !==를 제공합니다.
let name = "world"
if name == "world" {
    print("hello, world")
} else {
    print("I'm sorry \(name), but I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".


let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
    rowHeight = contentHeight + 50
} else {
    rowHeight = contentHeight + 20
}
// rowHeight는 90입니다.

let defaultColorName = "red"
var userDefinedColorName: String?   // 이 값은 defaults 값 nil입니다.

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorNam이 nil이므로 colorNameToUse 값은 defaultColorName인 "red"가 설정 됩니다.

a != nil ? a! : b
=>nil 병합 연산자는 a ?? b 형태를 갖는 연산자 입니다. 옵셔널 a를 벗겨서(unwraps) 만약 a가 nil 인 경우 b를 반환합니다. 이 nil 병합 연산자는 위 코드의 축약형입니다.

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName가 nil이 아니므로 colorNameToUse 는 "green"이 됩니다.

범위연산자
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

(a..<b)의 형태로 a부터 b보다 작을 때까지의 범위를 갖습니다. 즉, a부터 b-1까지 값을 갖습니다. 이건 어디서 많이 본 범위! 그렇습니다. 보통 배열이 배열의 크기 - 1의 인덱스를 갖기 때문에 이 반 닫힌 범위 연산자는 배열을 다루는데 유용합니다. 다음은 관련 예제입니다.

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

[a..] [..a]의 형태로 범위의 시작 혹은 끝만 지정해 사용하는 범위 연산자 입니다. 지정한 시작 값 혹은 끝 값은 범위에 포함됩니다. 다음은 관련 예제 입니다.

for name in names[2...] {
    print(name)
}
// Brian
// Jack

for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian

contains는 문자열이나 배열에
특정 문자가 속해있는지 문자열 포함여부를
Boolean값으로 리턴해주는 함수입니다.
[출처] 스위프트[Swift] - contains 사용하기|작성자 홍군

var Color=["red" , "Blue", "Green"]
var inserC1="gray"
var inserC2="red"

var isContaion1 = Color.contaions(insertC1) //false
var isContaion2 = Color.contaions(insertC2) // true

여러줄의 문자열을 사용하고 싶은 경우 큰 따옴표 3개(“””)로 묶어서 사용할 수 있습니다.

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."
"""
여러줄 문자열을 사용할 때는 첫 시작의 """ 다음 줄부터 마지막 """의 직전까지를 문자열로 봅니다. 그래서 아래 두 줄의 표현으로 이루어진 singleLineString과 multilineString은 같은 값을 갖게 됩니다.

let singleLineString = "These are the same."
let multilineString = """These are the same."""

여러줄 문자열을 사용하며 줄바꿈을 하고 싶으면 백슬래쉬(\)를 사용합니다.

빈 문자열 초기화 아래 예의 두 변수의 문자열 값은 같습니다.
var emtpryString = ""
var anotherEmptyString = String()

문자열이 비어있는지 여부를 확인하기 위해서는 isEmpty 프로퍼티를 이용합니다.
if emptyString.isEmpty {
    print("Nothing to see here")
}
// Prints "Nothing to see here"


var variableString = "Horse"
variableString += " and carriage"
// variableString = Horse and carriage

let constantString = "Highlander"
constantString += " and another Highlander"
// 문자열 상수(let)로 선언돼 있어 에러발생!

var는 수정가능. let은 에러발생.

https://okky.kr/article/827838

  let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
  print("unusualMenagerie has \(unusualMenagerie.count) characters")
  // "unusualMenagerie의 문자는 40개"

count를 사용 문자의 갯수를 측정할 수 있다.

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] // 에러!
greeting.index(after: greeting.endIndex) // 에러!

문자열의 개별 문자를 접근하기 위해서는 indices 프로퍼티를 사용합니다.
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
// G u t e n  T a g !

문자의 삽입과 삭제.
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome : hello!

welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome : hello there!

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome : hello there

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome : hello

부분 문자열
let greeting = "Hello, World!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning : Hello

// SubString인 beginning을 String으로 변환
let newString = String(beginning)

substring은 해당 문자를 직접 갖고 있는 것이 아니라 원본 String의 메모리를 참조해 사용함.

아래 코드는 문자열 배열에서 접두어 Act 1이 몇개가 들어있는지 확인하는 코드
var act1SceneCount = 0
for scene in remeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        act1SceneCount += 1
    }
}
print("There are \(act1SceneCount) scenes in Act 1")
// There are 5 scenes in Act 1

hasPrefix : 문자열이 어떤 글자로 시작하는지 확인
hasSuffix : 문자열이 어떤 글자로 끝나는지 확인

var mansionCount = 0
var cellCount = 0
for scene in remeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        mansionCount += 1
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        cellCount += 1
    }
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// 6 mansion scenes; 2 cell scenes

jusung.gitbook.io/the-swift-language-guide/language-guide/04-collection-types