[Swift]Array and Dictionary

0
30

Swift Programming


  • Array/Dictionary Declaration
  • Array/Dictionary Access
  • Initializer Call

Keywords : Swift, Array, Dictionary, Declaration, Access, Initializer, 스위프트, 배열, 딕셔너리, 선언, 접근, 생성자

Array Declaration

To declare Array/Dictionary is performed as below. var is a keyword to declare variable type identifier so we can add/delete/modify the values in the array/dictionary. But constant keyword let can’t help us do it.

var Identifier: [Type] = Initial values
var language: [String] = [“English”, “Korean”, “Japanese”]

1
2
3
4
5
6
7
//Basic Declaration
var languages: [String= [“English”“Korean”“Japanese”]
var capitals: [StringString= [
“Korea”“Seoul”,
“Japan”“Tokyo”,
“China”“Beijing”,
]
cs

*Swift’s implicit declaration helps us not focus on the Type of variables or constants. It’s automatically calculated by looking at the Type of values in the Array or Dictionary.

1
2
3
4
5
6
var languages = [“English”“Korean”“Japanese”//String
var capitals = [
    “Korea”“Seoul”,
    “Japan”“Tokyo”,
    “China”“Beijing”,
// String : String
cs

Array Access

If you are to access the array or dictionary you made, you may use [] to get to the index that you want to go to. Also, please refer to the way how to add/delete/modify by simply looking at the codes below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Access
languages[0//English
languages[1//Korean
capitals[“Korea”//Seoul
capitals[“Japan”//Tokyo
//Add
capitals[“France”= “Paris”
languages.append(“French”)
//Delete
capitals[“Korea”= nil
capitals.removeValue(forKey: “Japan”)
languages.remove(at: 0)
cs

Initializer Call

If you plan to make empty array or dictionary and then play with them, you have to call Initializer with parenthesis().

1
2
3
4
5
var languages: [String= []
var capitals: [StringString= [:]
//or
var languages = [String]()
var capitals = [StringString]()
cs

If you didn’t mistakenly define parenthesis, you have to call initializer before you use that array or dictionary or you can’t access any method, value of that array.

1
2
3
4
5
6
7
8
var languages: [String]
var capitals: [StringString]
languages = [String]()
languages.append(“Korea”)
capitals = [String:String]()
capitals[“Korea”= “Seoul”
cs

 

LEAVE A REPLY