반응형

let을 사용하여 상수를 만들고 var를 사용하여 변수를 만듭니다. 



A Swift Tour ( https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html  ) 문서의 코드를 Swift Playground(  https://swiftfiddle.com/ ) 에서 실행시켜 보며 진행해보았습니다. 

 

본 문서는 공부한 내용을 정리하는 목적으로 작성되었으며 A Swift Tour 문서의 내용을 바탕으로 하고 있습니다. 잘못된 점이 있을 수 있습니다



2021. 10. 05   최초작성 

2021. 10. 20   값없는 변수 선언 가능한 점 추가 

2021. 11. 02   접속 불가 상태인 Swift Playground 사이트 변경

2022. 10. 22   최종 수정



상수는 값에 이름을 부여하는 것입니다. 상수에 한번 값을 대입할 수 있으며 2번이상 상수에 값을 대입하게 되면 아래와 같은 에러가 납니다. note 메시지로 let 대신에 var를 사용하라고 조언해주고 있습니다. 여러 번 값을 대입하는 경우에는 변수를 사용하라는 것입니다. 

let myConstant = 42
myConstant = 10

 

main.swift:4:1: error: cannot assign to value: 'myConstant' is a 'let' constant
myConstant = 10
^~~~~~~~~~
main.swift:3:1: note: change 'let' to 'var' to make it mutable
let myConstant = 42
^~~
var

 

상수에 값이 대입되면 여러 곳에서 상수에 저장된 값을 사용할 수 있습니다. 다음 예제는 상수 myConstant의 값을 3개의 print문을 사용하여 출력하고 있습니다. 

let myConstant = 42
print(myConstant)
print(myConstant)
print(myConstant)

 

42
42
42

 

변수는 var 키워드를 사용하여 생성합니다. 상수와 달리 변수 생성 후, 다시 값을 대입하는 것이 가능합니다. 

var myVariable = 42
print(myVariable)

myVariable = 50
print(myVariable)

 

myVariable 변수에 42를 처음 대입했을 때와  myVariable 변수에 50을 대입했을 때 각각 myVariable  변수를  출력해보면 다르게 출력되는 것을 볼 수 있습니다. 

42
50

 

변수의 타입을 지정하지 않고 값 대입 없이 변수를 생성하면 에러가 발생합니다.

var myVariable

 

main.swift:3:5: error: type annotation missing in pattern
var myVariable
    ^

 

값없는 변수를 선언을 하려면 다음처럼 변수 타입을 지정해줘야 합니다.  나중에 값을 변수에 대입하여 사용할 수 있습니다. 

var str: String

str = "hello"

print(str)

 

상수 또는 변수에 데이터 타입을 지정했다면 동일한 데이터 타입의 값을 상수 또는 변수에 대입해야 합니다.  항상 명시적으로 타입을 적을 필요는 없습니다.

상수 또는 변수를 생성할 때  대입된 값을 컴파일러에서 보고  해당 타입을 추측합니다.  묵시적(implicit) 선언 이라고 합니다.

 

다음 두 상수는 대입된 값을 보고 각각 Int 타입과 Double 타입이 됩니다. 추가 코드를 사용하여 상수의 타입을 출력해봅니다. 

let implicitInteger = 70
print(type(of: implicitInteger), implicitInteger)

let implicitDouble = 70.0
print(type(of: implicitDouble), implicitDouble)

 

print문에 type(of: 상수이름) 을 사용하여 상수의 타입을 출력하고 옆에 해당 상수를 같이 출력했습니다. 

출력 결과에서 각 상수가 대입된 값에 따라 Int 타입, Double 타입이 된 것을 볼 수 있습니다.  

상수가 아닌 변수에 대해 type(of: 변수이름)처럼 사용하는 것도 가능합니다.

Int 70
Double 70.0

 

EXPERIMENT

값이 4인 Float 타입의 상수를  명시적(Explicit)으로 생성해봅니다. 

let ExplicitFloat: Float = 4
print(type(of: ExplicitFloat), ExplicitFloat)

 

Float 4.0

 

같은 이름의 변수를 두번 생성하려고 하면 에러가 납니다.

var myVariable = 10
var myVariable = 15

 

main.swift:4:5: error: invalid redeclaration of 'myVariable'
var myVariable = 15
    ^
main.swift:3:5: note: 'myVariable' previously declared here
var myVariable = 10
    ^

 

콜론으로 구분하여 변수 뒤에 데이터 타입을 지정할 수 있습니다. 정수 70을 Double형 데이터 타입으로 저장하기 위해 변수 뒤에 Double라고 명시해주었기 때문에 변수 explicitDouble 에 정수 70을 대입했지만 print문으로 변수를 출력해보면 소수점이 있는 실수값 70.0 입니다. 

let explicitDouble: Double = 70
print(explicitDouble)

 

70.0

 

상수 또는 변수에 저장된 값은 묵시적으로 다른 타입으로 변환되지 않습니다. 

예를 들어 아래 코드처럼 String 타입의 변수 label과 Int 타입의 변수 width를 + 기호로 결합하더라도 int 타입의 변수 width가 묵시적으로 String 타입으로 변환되지 않는다는 의미입니다.  

let label = "The width is "
let width = 94
let widthLabel = label + width

print(widthLabel)

 

실행결과 String 타입의 변수 label과 Int 타입의 변수 width를 + 기호로 결합한 부분에서 에러가 발생했습니다.

main.swift:5:24: error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'
let widthLabel = label + width
                 ~~~~~ ^ ~~~~~
main.swift:5:24: note: overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)
let widthLabel = label + width
                       ^

 

상수 또는 변수에 저장된 값을 다른 타입으로 변환해야 하는 경우 다음 예제처럼 명시적으로 변환할 타입을 지정해줘야 합니다.

Int 타입의 변수 width를 String타입으로 변환해주고 있습니다. 

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

print(widthLabel)

 

에러 없이 String 타입의 변수 label에 저장된 값에 Int 타입의 변수 width에 저장된 값이 결합되어 화면에 출력되었습니다.

The width is 94

 

문자열에 변수 또는 상수값을 포함시켜 출력하는 간단한 방법이 있습니다. 

변수 또는 상수 이름을 괄호안에 적고 괄호 앞에 백슬래시(\)를 적어주면 됩니다.

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

print(appleSummary)
print(fruitSummary)

 

상수 apples의 값과 상수 apples와 상수 oranges를 더한 값이 각각 문자열과 같이 출력되었습니다. 

I have 3 apples.
I have 8 pieces of fruit.

 

EXPERIMENT

백슬래시(\)를 사용하여 실수 계산을 포함한 출력과 문자열 변수를 포함한 출력을 만들어 봅니다. 

let A = 1.2
let B = 2.5
let world = "세상아"
let strAB = "\(A) + \(B) = \(A+B)"
let strHello = "안녕 \(world) !"

print(strAB)
print(strHello)

 

1.2 + 2.5 = 3.7
안녕 세상아 !

 

세 개의 큰따옴표(""")를 사용하여 여러 줄로 구성된 문자열을 변수 또는 상수에 대입할 수 있습니다.

다음 예제 코드처럼 입력된 문자열의 들여쓰기가  닫는 인용 부호의 들여쓰기와 일치하면  각 줄의 시작 부분에 있는 들여쓰기가 제거됩니다. 

let apples = 2
let oranges = 5

let quotation = """
          I said "I have \(apples) apples."
          And then I said "I have \(apples + oranges) pieces of fruit."
          """

print(quotation)

 

실행결과 들여쓰기가 없이 두  문장이 출력되었습니다.

I said "I have 2 apples."
And then I said "I have 7 pieces of fruit."

 

대괄호([])를 사용하여 배열 및 딕셔너리를 만듭니다.  대괄호 안에 인덱스 또는 키를 적어 배열 및 딕셔너리의 요소에 접근할 수 있습니다.  배열 또는 딕셔너리의 마지막 요소 뒤에 쉼표를 사용할 수 있습니다. 

// 3개의 문자열을 원소로 갖는 배열 shoppingList를 선언합니다.
var shoppingList = ["catfish", "water", "tulips"]

// 배열 shoppingList의 첫번째 원소를 출력합니다.
print(shoppingList[0])


// 배열 shoppingList의 두번째 원소의 값을 변경합니다.
shoppingList[1] = "bottle of water"



// 두개의 원소를 갖는 딕셔너리 occupations를 선언합니다.
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]


// 딕셔너리 occupations에서 key가 Malcolm인 원소의 값을 출력합니다.
print(occupations["Malcolm"])


// 딕셔너리 occupations에서 key가 Jayne인 원소의 값을 변경합니다.
occupations["Jayne"] = "Public Relations"

 

catfish
Optional("Captain")

 

배열의 append 메소드를 사용하여 배열에 원소를 추가할 수 있습니다.

var shoppingList = ["catfish", "water", "tulips"]
print(shoppingList)


// 배열 shoppingList에 원소를 추가합니다.
shoppingList.append("blue paint")
print(shoppingList)

 

["catfish", "water", "tulips"]
["catfish", "water", "tulips", "blue paint"]

 

빈 배열이나 빈 딕셔너리를 만들려면 이니셜라이저 구문을 사용하십시오.

빈 배열이나 빈 딕셔너리 생성시 지정한 데이터 타입의 원소를 추가하지 않으면  에러가 발생합니다. 

// 빈 배열 emptyArray를 선언합니다.
var emptyArray: [String] = []

// 빈 딕셔너리 emptyDictionary를 선언합니다.
var emptyDictionary: [String: Float] = [:]


// 배열 emptyArray에 원소를 추가합니다.
emptyArray.append("blue paint")


// 딕셔너리 emptyDictionary에 원소를 추가합니다.
emptyDictionary["abc"] = 10.0

print(emptyArray)
print(emptyDictionary)

 

["blue paint"]
["abc": 10.0]

 

빈 배열이나 빈 딕셔너리 선언시 데이터 타입을 지정해주지 않으면 에러가 발생합니다. 

var shoppingList = []
var occupations = [:]

 

main.swift:3:20: error: empty collection literal requires an explicit type
var shoppingList = []
                   ^~
main.swift:4:19: error: empty collection literal requires an explicit type
var occupations = [:]
                  ^~~




Swift 강좌 1 - Hello, world

https://webnautes.tistory.com/1549



Swift 강좌 2 - 상수와 변수

https://webnautes.tistory.com/1550



Swift 강좌 3 - 제어문 : if, for - in, switch, repeat - while

https://webnautes.tistory.com/1551



Swift 강좌 4 - 함수

https://webnautes.tistory.com/1552



Swift 강좌 5 - 객체(Objects)와 클래스(Classes)

https://webnautes.tistory.com/1558



Swift 강좌 6 - 열거형(Enumerations)과 구조체(Structures)

https://webnautes.tistory.com/1559



Swift 강좌 7 - 프로토콜(Protocols)과 익스텐션(Extensions)

https://webnautes.tistory.com/1562



Swift 강좌 8 - 에러 처리(Error Handling)

https://webnautes.tistory.com/1566



Swift 강좌 9 - 제네릭(Generics)

https://webnautes.tistory.com/1568

 

반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts