DEV Community

Sydney Andre
Sydney Andre

Posted on • Updated on

Apple's Programming Language: Swift

In my last article, we took a look at mobile app development--how it is different from web development, approaches, and took a quick look at two languages, Swift and Java, that are often used for native app development. In this article, we will take a deep dive into Swift learning more about its histories and basic language features.

History

Swift was released in 2014 by Apple, but brainstorming began in 2010 by Chris Lattner and other Apple developers. Before its creation, the primary language for Apple's operating systems was Objective-C. In their announcement, Apple explains the impetus for creating Swift was to have a language that overcame the shortfalls of Objective-C. They wanted a faster, safer, and more modern and interactive language. A common misconception is that Swift only supports Apple's operating systems, but it also can support Linux, Windows, and Android OS.

Some key characteristics that set Swift apart are its safety and interactivity. By safety, they are referring to type safety. Apple claims making many common programming such as uninitialized variables, copy/reference errors, and unsafe string formatting are impossible with Swift. When writing Swift in Xcode, you have access to Swift Playgrounds which is basically a real time REPL. As you code, your results appear immediately, and you can view what your results would be over the execution of the code.

Now that we know a bit more about its history, let's learn a bit more about the language!

Language Features

Datatypes
Swift includes fundamental types such as integers, floating-point values, booleans, and strings and three primary collection types including ordered collections, known as arrays, unordered collections of unique values, known as sets, and unordered collections of key/value pairs known as dictionaries. An interesting feature of these collection types is that all values in the array or set must be of the same type. Similarly, in dictionaries, all of the keys must have the same type and all of the values must have the same type.

Variables and Constants
Similar to other languages, Swift utilizes constants and variables to associate names with a value of a specific datatype. As the name might suggest, values declared as constants with the keyword let stay constant and cannot be changes; whereas, values declared as variables with the keyword var can change values later in the program. Additionally, you can add type annotation to define the datatype of the variable or constant, although this is not necessary in practice because of Swift's type inference. You can also declare more than one variable or constant on one line. Let's take a look at an example.

//declaring constants
let name = 'Georgia', age = 8, isCute = true
name = 'Sydney' /* this would result in an error as constants 
cannot be redefined */

//declaring variables
var numOfTreats = 3, bestFriend = 'Reggie', isHungry = false
numberOfTreats = 5
bestFriend = 'Sydney'
isHungry = 'sometimes' /*this would result in an error
because variables cannot be reassigned to a value of a
different type */
Enter fullscreen mode Exit fullscreen mode

Unlike these simple data types, when declaring a collection, you must define the type of values you intend to use. The example below shows the syntax that is used.

//arrays
var favFruits: [String] = ['strawberry', 'raspberry',
bananas', 'raspberry']
favFruits = [4, 7, 9] //this would result in an error
//although it can be reassigned, the new 
values must be of the same type.

//sets
var favColors: Set<String> = ['blue', 'green', 'pink']
favColors = ['blue', 'blue', 'green']
//this would result in a error because sets must contain
 unique values

//Dictionaries 
var bio: [String: String] = [name: 'Georgia', 
hometown: 'Baton Rouge', birthMonth: 'March']
Enter fullscreen mode Exit fullscreen mode

Collections
Now that we know some of the intricacies of collections in Swift. Let's explore how we can access and modify each of these types of collections.

You can access the number of elements in any of these types by using the .count property. Let's use this property on our previously declared collections to see how many elements are in each.

favFruits.count //results in 4
favColors.count //results in 3
bio.count //results in 3
Enter fullscreen mode Exit fullscreen mode

Similarly, all collections have an isEmpty property that will result in a boolean values. The syntax works the same as the .count property.

Arrays
Similar to bracket notation in JavaScript, you can access values at specific indexes by passing the index of the value you want in brackets directly after the array name. Additionally you can use a similar syntax to change an element in your variable array. Unlike JavaScript, the index you input must be valid, you cannot pass in an expression.

//retrieve the first element
favFruits[0] //strawberry

//change the second element
favFruit[1] = 'blueberry'

//add to the end
favFruit[favFruit.count] = 'oranges' //will result in an error
Enter fullscreen mode Exit fullscreen mode

You can insert and remove values from an array by a specific index using the insert or remove methods or values can be added or removed from the end of an array with the .append and removeLast() methods. Additionally we can add another array to the end of an array using the += operator.

favFruits.insert('grapes', at: 2)
favFruits.remove(at: 1)
favFruits.append('cherry')
favFruits += ['apple', 'grapefruit']
favFruits.removeLast()
favFruits.count //8
Enter fullscreen mode Exit fullscreen mode

After all of this modifying, what do you think favFruits looks like now? If you answered ['strawberry', 'blueberry', 'grapes', 'raspberry', 'bananas', 'raspberry', 'cherry', 'apple'], great! You have been paying close attention.

Sets
Now let's look at sets. Sets are unordered collections of non-repeating values. This means we cannot access values with indexes, but we still have methods to modify sets. Sets have .insert, .remove, and .removeAll methods that allow us to modify. We can also check if a value is present with the .contains method. Let's look at our favColors set again!

favColors.insert('yellow') 
favColors.remove('green')
favColors.contains('blue') //true
//What does fav colors look like now?
//['blue', 'pink', 'yellow']
Enter fullscreen mode Exit fullscreen mode

Dictionaries
You can update or add a new value to a dictionary in one of two ways. Updating and adding a value, look the same syntacticly. Whether the pair is updated or added depends on if they key that is used is already in the dictionary. To remove a value, simply use the same subscript syntax to update a value, but instead set that value equal to nil. Let's take a look at our bio dictionary that was declared previously.

//subscript syntax
bio[hometown] = 'New Orleans' //hometown was updated from Baton Rouge 
to New Orleans
bio[favColor] = 'green' //favColor key was added

//updateValue method
bio.updateValue('pink', forKey: 'favColor') //changed from green 
to pink
bio.updateValue('cookie', forKey: 'favSnack') //favSnack key was added

//remove a pair
bio[favColor] = nil
Enter fullscreen mode Exit fullscreen mode

When the updateValue method is used, it returns the value that was at that key before the update.

Conclusion

Swift has a lot to offer in terms of syntax simplicity, safety, and interactivity. Many say it is a great beginner language for because of this. Because of its similarities to C family languages, it is easy for seasoned programmers to pick up on and is a great tool to have on your tool belt as Apple is one of the most widely known and influential technology companies of our time.

Sources

https://developer.apple.com/swift/
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/
https://www.swift.org/getting-started/
https://www.extremetech.com/computing/183563-apples-new-swift-language-explained-a-clever-move-to-boost-ios-while-holding-android-apps-back
https://en.wikipedia.org/wiki/Swift_(programming_language)
https://exyte.com/blog/introduciton-to-swift

Top comments (0)