The Basics of Swift: A Beginner’s Perspective

// Use two forward slashes for a single-line comment

/* Use a forward slash followed by an asterisk to start a multi-line comment.
To end the multi-line comment, use an asterisk followed by a forward slash. */

/* Did you know it’s also possible to nest comments in Swift?
/* You can nest comments by starting a multi-line comment, then starting another. */
Finally, close the last (two) comments */

These examples demonstrate how to write different types of comments in Swift. As you might be aware, Swift is a new OS X and iOS programming language announced this week at WWDC. After hearing the announcement, I immediately wanted to check it out because I enjoy coding iOS apps, even though I’m only a beginner (experienced programmers write a large majority of the code in our company’s apps :-) ). With that in mind, I heard Apple mention Swift is easier for beginning programmers to learn. But, I was still skeptical.

Ever since I started coding over a year ago, I have found the learning process difficult–and darn right daunting at times– almost every step of the way. Thankfully, I can tell you after reading “The Basics” chapter in the Swift Language Guide (FREE on iBooks), I quickly recognized familiar concepts. My experiences with writing Objective-C (for iOS apps) and Javascript (for websites) made me feel right at home with comments, variables, strings, booleans, loops, conditionals, etc. Yet, there was still a good amount for me to learn in the first chapter. Fortunately, it was explained in an Apple way that made a lot of sense. Here are some of the basics that I learned:

// Constants and Variables
/* Constants use a let keyword, and don’t change. Variables, on the other hand, use a var keyword, and can change.
1st example below is saying, declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10 */
let maximumLoginAttempts = 10;
// 2nd example is saying, declare a variable called currentLoginAttempt, and give it an initial value of 0
var currentLoginAttempt = 0;
// With Type Annotation, it’s possible to specify the type of constant or variable you’re declaring. For e.g., you can declare a variable called welcomeMessage that is of type String.
var welcomeMessage: String
welcomeMessage = “Hello”
// In practice, you would rarely provide the type annotation for a constant or variable. Instead, you would provide an initial value, then the system would “type infer” the value automatically. Here’s an example of a String literal showing how the value is assigned when declaring the variable,
var initialMessage = “Hi”

// Once you have declared a variable, you can change the value. However, you can’t redeclare it with the same name, or change it to store values of a different type. Nor can you change a variable to a constant (or vice versa, for that matter). For example you CAN do this,
var test = “This is a test”
test = “This is another test”
// You can also use the “print” function or “println” (adds a line break) to output the value of the variable to the console
print(“We can say \(test)”) // prints “We can say This is another test”

// However, you CAN’T do any of these,
var test = “This is yet another test” // CAN’T redeclare the variable named “test”
var test = 2 // CAN’T change the String type to an Int
let test = “This is once again another test” // CAN’T change the variable to a constant
// If you do any of these, you will receive an error, and you will not be able to compile your code. Consequently, you won’t be able to run your program.

// Semicolons
// Other languages require a semicolon at the end of each line, but it’s optional in Swift. Both of the following lines are acceptable:
let cat = “orange”
let dog = “black”;

// Integers
// There are different types of integers (e.g., Int, Int32, UInt), but Int is recommended in most cases to avoid the need for converting different number types.

// Numeric Literals
// If you combine integer and floating-point literals (values assigned at the time of declaring them), a Double (floating-point type) will be type inferred. For example,
let anotherPi = 3 + 0.14159
println(anotherPi) // prints 3.14159

// Numeric Type Conversion
// If you have an integer and a floating-point that were declared separately, then you want to combine them in an expression, you must specify the type. For example,
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine

// When converting from a floating-point to an integer, an integer type can be initialized with a Double or Float value. For example,
let integerPi = Int(pi) // In this way, the floating-point value is truncated from 3.14159 to 3

// Booleans
// Boolean type called Bool. Bool can either be true or false. If you initialize the Bool, the system can infer type Bool. For example,
let orangesAreOrange = true

// Tuples
// Tuples group multiple values in one compound value. The values can be of different types. For example,
let http404Error = (404, “Not Found”)
// You can decompose a tuple’s contents into separate constants or variables
let (statusCode, statusMessage) = http404Error
println(“The status code is \(statusCode)“) // prints “The status code is 404″
println(“The status message is \(statusMessage)“) // prints “The status message is Not Found”
println(“The status code is \(http404Error.0)“) // prints “The status code is 404

// Alternative to let http404Error = (404, “Not Found”), you can name the elements in the Tuple to access the values of those elements. For example,
let http200Status = (statusCode: 200, description: “OK”)
println(“The status message is \(http200Status.description)“) // prints “The status message is OK”

// Optionals
/* Optionals allow you to indicate the absence of a value for any type at all, not just objects (as in C or Objective-C)
Let’s look at the String type toInt method, and attempt to convert a String to an Int. Since it would work if an Int is wrapped in a String, but it won’t if another value such as “hello, world” is the String value. So, an optional Int, or “Int?”, is inferred. */
let possibleNumber = “123″
let convertedNumber = possibleNumber.toInt() // convertedNumber is inferred to be of type “Int?”, or “optional Int”
// Forced unwrapping (add a ! to the end of the constant/variable name) – if an optional definitely has a value, please use it
if convertedNumber {
println(“\(possibleNumber) has an integer value of \(convertedNumber!)“)
} else {
println(“\(possibleNumber) could not be converted to an integer”)
}
// prints “123 has an integer value of 123″

So far in the Swift Language Guide, it appears that Apple is making computer programming as accessible as possible. The Swift Language Guide is free, and it does a great job of teaching the language. Clear examples are provided with easy-to-understand explanations. It might help to have prior experience with a programming language such as C, Objective-C, or Javascript, but Swift is a learning process for everyone, including experienced programmers.  So, I hope that even beginners like me will stick with learning how to write Swift code.