DEV Community

Donn
Donn

Posted on

Learning Swift Basics

I've started a new journey in becoming a mobile software engineer, specifically I'm learning Apple's Swift, a language used in their mobile app development, (and also their other platforms). I briefly started in Kotlin (used for Android app development), but I see a lot of overlap between the two languages.

Swift has some interesting ways to store and access data, including arrays, sets and dictionaries, to just name a few. We'll walk through the aforementioned datatypes, and explore their differences.

Array: Arrays should be a familiar topic, since every language seems to have this datatype. Arrays in Swift stores data in order, and allows for duplicates. Arrays only allow one type data, whether it's String, Int, Bool, etc.

Creating empty Arrays:

var array1: [String] = [String]()
var array2: [String] = []
var array3 = Array<String>()
Enter fullscreen mode Exit fullscreen mode

Set: Sets are very similar to arrays; both store only one type of data at a time, but some key differences are that sets have no set order in how they store data, and duplicates are not allowed in sets.

Creating empty Sets:

Var set = Set<String>()
Enter fullscreen mode Exit fullscreen mode

Dictionary: Dictionaries allows for customization in how data is stored in what is called "key: value" pairs. These pairings can be stored in a number of ways, such as [String: String], [Int: String], [Int: Bool]. Since Swift doesn't know how far any given dictionary extends, one extra step needs to be taken in case the key being accessed doesn't exist. When attempting to access the value of a key, a default value needs to be set:

dic["color", default: "Unknown"]

Creating empty Dictionaries

var dic1 = [String: String]()
var dic2 = Dictionary<String, Int>()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)