Swift) 변수, 상수, 배열, Dictionary

2019. 9. 29. 21:29Swift

반응형

변수: var

상수: let

 

var str = "Hello, playgroundff"

str = "Hello, playgroundffffff"

 

print(str)

var implicitInteger = 80 //타입을 지정하지 않으면 처음 넣는 값이 타입으로 정해짐

let implicitDouble = 70.0

let explicitDouble:Double = 70 

 

var k:String

//k="test" //error띄어쓰기까지 check

k = "test"

//k = 0 //error 이미 string타입으로 정해졌기때문에 int형의 값을 넣을 수 없음

 

var kk : Int

//kk = 9.0 //error 자동 형변환 없음

kk = 9

 

var j : Double

j = 9.1

j = 10 //*Double형에 int값은 허용함

 

문자열에 변수함께 출력하기

let label = "The width is "

let width = 98

//let widthLabel = label + width

//error. Binary operator '+' cannot be applied to operands of type 'String' and 'Int'

let widthLabel = label + String(width)

print(widthLabel) // The width is 98

 

*좀 더 간단한 방법

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples"

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

print(fruitSummary) //I have 8 pieces of fruit

//use \() to include a floating-point calculation in a string

 

*문자열내에 "사용하기&줄바꿈

let quotaion = """

I said "I have \(apples) apples."

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

"""

print(quotaion)

 I said "I have 3.0 apples."

 And then I said "I have 8.9 pieces of fruit."

//Use three double quotation marks (""") for strings that take up multiple lines

 

배열

var shoppinglist = ["catfish","water","tulips"]

shoppinglist.append("blue paint")

print(shoppinglist) //["catfish", "water", "tulips", "blue paint"]

 

shoppinglist[3] = "fffff"

//shoppinglist[4] = "fffffff" 아직없는 인덱스엔 넣을 수 없음

print(shoppinglist) //["catfish", "water", "tulips", "fffff"]

 

let emptyArray = [String]()

 

shoppinglist = []

shoppinglist.append("000")

print(shoppinglist) //["000"]

 

Dictionary

let emptyDictionary = [String: Float]() //[key type: value type]

 

var occupations = [

    "Malcolm": "Captain",

    "Kaylee":"Mechanic"

]

 

occupations["jayne"] = "Public Relations"

//array와 달리 dictionary는 새로운 키 사용가능

 

//occupations=[] error

occupations=[:] //빈 dictinary로

//occupations = [String:Float] //error, 타입변경은 안됨

 

//occupations["json"] = 88.8 //error, String값만 넣을 수 있음

occupations["json"]

occupations["json"] = "Friend"

print(occupations) //["json":"Friend"]

 

반응형

'Swift' 카테고리의 다른 글

Swift) object & class  (0) 2019.12.01
Swift) function  (0) 2019.12.01
Swift) if-else, 반복문(for, for-in, while ..)  (0) 2019.10.06