Created
November 2, 2016 09:00
-
-
Save bllmo/4bce8fd0b765a9723c0aad1a13ed38f6 to your computer and use it in GitHub Desktop.
Swift Fundamental
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* # Hello World | |
* | |
* It is common to start any tutorial for a new language with the Hello World | |
* example so we'll start out by showing how easy this is to do in Swift: | |
*/ | |
print("Hello World") | |
/* | |
* To make this a little more personal, let's look at one of the handy | |
* features of Swift (called string interpolation) where we can insert values into strings using the \(...) syntax. | |
* Below, we've inserted name into the middle of our string: | |
*/ | |
let name: String = "Bob" | |
print("Hello \(name)!") | |
/* | |
* # When to use let vs var | |
* | |
* You'll notice in the example above we've used let to create the new variable for the name "Bob". | |
* In Swift, you'll choose from the following 2 options when creating a new variable: | |
*/ | |
let numberOfContinents: Int = 7 | |
var continentsVisited: Int = 2 | |
/* | |
* # Numbers | |
* | |
* The two most common types of numbers you'll use in Swift are integers (Int) and doubles (Double): | |
*/ | |
let minValue: Int = -42 | |
let maxValue: Int = 55 | |
let pi: Double = 3.14159 | |
let billAmount: Double = 10.25 | |
/* | |
* # Strings | |
* | |
* Strings represent a series of characters: | |
*/ | |
let hello: String = "Hello" | |
let world: String = "World" | |
let helloWorld: String = "\(hello) \(world)" | |
/* | |
* # Booleans | |
* | |
* Boolean is a very simple type in Swift as it can only ever be true or false: | |
*/ | |
let swiftIsCool: Bool = true | |
let iMissObjectiveC: Bool = false | |
/* | |
* # Arrays | |
* | |
* Arrays store a list of values that must be of the same type. | |
* Below we've kept track of the previous bill amounts (which is a list of doubles): | |
*/ | |
var previousBillAmounts: [Double] = [10.25, 21.32, 15.54] | |
previousBillAmounts.append(52.45) | |
let count = previousBillAmounts.count | |
let firstBillAmount = previousBillAmounts[0] | |
/* | |
* # Dictionaries | |
* | |
* Much like you might use a real world dictionary to look up the definition for a word, | |
* you can use the dictionary data structure in Swift to create associations | |
* between keys (the word in the real world dictionary) and values (the definition in the real world dictionary). | |
*/ | |
var people: [String: [String: Int]] = [ "Bob": ["Age": 32], "Cindy": ["Age": 32] ] | |
people["Bob"]?["Age"] | |
/* | |
* # Specifying Types | |
* | |
* In most of the examples in this guide, we are explicit with the types of our constants and variables. | |
* Explicit typing looks something like: | |
*/ | |
let car: String = "Ford" | |
let color = "Red" | |
let height: Double = 3 | |
let age = 10.0 | |
/* | |
* # Any and AnyObject | |
* | |
* Swift has two special "catch all types" that come in handy when a more specific type cannot be determined. | |
* | |
* AnyObject can represent an instance of any class type. | |
* | |
* Any can represent an instance of any type at all. | |
* | |
* In general it's a best practice to be as specific with your types as possible and avoid the use of AnyObject and Any, but they become particularly | |
* helpful when interacting with Objective-C code that is less strict on typing. | |
*/ | |
let team: [String: Any] = ["Bob": "Software Engineering", "Cindy": ["Position": "Designer" ]] | |
/* | |
* # Optionals | |
* | |
* Optionals is a very important concept in Swift and is meant to improve the safety of Swift code. | |
* By simply placing a question mark (?) after any type, it declares that variable to be optional. | |
* An optional type allows that variable to exist in oneof the following two states: | |
* | |
* 1. There is a value and it equals x | |
* 2. There isn't a value at all | |
* | |
* Let's look at an example to make this more clear. Consider the following 2 examples where we are trying to convert a String to an Int: | |
*/ | |
let numbers: String = "123" | |
let optionalConvertedNumbers: Int? = Int(numbers) | |
let srings: String = "abc def" | |
let optionalConvertedSrings: Int? = Int(srings) | |
/* | |
* Swift requires optionalConvertedInput to be of type Int? (or "optional Int") | |
* so that it is explicit that convertedInput might not contain a value (in the case when the conversion fails). | |
* If we were to declare convertedInput as simply Int, we'd get a compile error. | |
* | |
* There's a handy syntax in Swift that you'll use quite often when working with optionals. | |
* If we wanted to use the value of optionalConvertedInput later on in our code, we'd have to first check to make sure it's not nil. | |
* We can do so using the following code: | |
*/ | |
let fibonacci: String = "11235" | |
let optionalConvertedInput: Int? = Int(numbers) | |
if let convertedInput = optionalConvertedInput { | |
print(convertedInput) | |
} else { | |
print("nil") | |
} | |
/* | |
* # Functions | |
* | |
* Functions in Swift are very similar to other languages. The simplest function in Swift can be written as: | |
*/ | |
func printHello() { | |
print("Hello!") | |
} | |
printHello() | |
/* | |
* We can extend this function to be a little more personable by taking in a name and returning | |
* the greeting instead of printing it out: | |
*/ | |
func sayHelloWithName(to firstPersonName: String, and secondPersonName: String) -> String { | |
return "Hello \(firstPersonName) and \(secondPersonName)!" | |
} | |
let greeting: String = sayHelloWithName(to: "Bob", and: "Cindy") | |
/* | |
* # Conditional Statements | |
* | |
* If statements are very similar to other languages and can be expressed as: | |
*/ | |
let temperatureInFahrenheit: Int = 90 | |
if temperatureInFahrenheit <= 32 { | |
print("It's very cold. Consider wearing a scarf.") | |
} else if temperatureInFahrenheit >= 86 { | |
print("It's really warm. Don't forget to wear sunscreen.") | |
} else { | |
print("It's not that cold. Wear a t-shirt.") | |
} | |
/* | |
* # Loops | |
* | |
* The two most common types of loops you'll need in Swift are for loops and for-in loops. | |
* For loops work well when you want to do something until a particular condition is met (in the case below until index >= 3): | |
*/ | |
for _ in 0..<3 { | |
print("Hello") | |
} | |
/* | |
* For-in loops come in really handy when you want to do something to each item in a collection (such as an array): | |
*/ | |
let names = ["Anna", "Alex", "Brian", "Jack"] | |
for name in names { | |
print("Hello, \(name)!") | |
} | |
/* | |
* Sometimes you want to loop over each item in an array and also keep track of the index of the item. | |
* Array's enumerate() method can help you achieve this: | |
*/ | |
let fruits = ["Apple", "Peach", "Banana"] | |
for (index, value) in fruits.enumerated() { | |
print("Item \(index + 1): \(value)") | |
} | |
/* | |
* # Classes | |
* | |
* Classes are the building blocks of your app’s code. You define properties and methods to add | |
* functionality to your classes by using the same syntax as for variables and functions. | |
* | |
* Below you can find a Person class that is meant to show an example of the types of things you'll want | |
* to do when building your classes. | |
*/ | |
class Person { | |
init(firstName: String, lastName: String) { | |
self.firstName = firstName | |
self.lastName = lastName | |
} | |
var firstName: String | |
var lastName: String | |
var fullName: String { | |
get { | |
return "\(firstName) \(lastName)" | |
} | |
} | |
} | |
let bob = Person(firstName: "Bob", lastName: "Smith") | |
bob.fullName | |
/* | |
* # Protocols | |
* | |
* Protocols are similar to interfaces in other languages. Think about a protocol as a contract. | |
* The contract includes a set of methods that must be implemented. | |
* Any classes that choose to implement a protocol | |
* sign this contract and implement all the methods that are in the protocol. | |
*/ | |
protocol MyFriendlyGreeterProtocol { | |
func sayHello() | |
func sayBye() | |
} | |
class MyEnglishPerson: MyFriendlyGreeterProtocol { | |
func sayHello() { | |
print("Hello!") | |
} | |
func sayBye() { | |
print("Bye!") | |
} | |
} | |
/* | |
* # Closures | |
* | |
*/ | |
func makeIncrementer(forIncrement amount: Int) -> () -> Int { | |
var runningTotal = 0 | |
func incrementer() -> Int { | |
runningTotal += amount | |
return runningTotal | |
} | |
return incrementer | |
} | |
let incrementByTen = makeIncrementer(forIncrement: 10) | |
incrementByTen() | |
/* | |
* # Type Casting (as, as?, as!) | |
* | |
* Type casting changes the type of a particular instance to another compatible type. | |
* There are 3 ways to accomplish this with Swift: | |
*/ | |
let myFloat = 1 as Float | |
/* | |
* # Understanding the Question Mark (?) | |
* | |
* There are various places where you'll come across the need for using question marks in your code. | |
* The following examples are meant to capture the major types of use cases for the question mark operator | |
* that can cause confusion when first learning Swift. | |
*/ | |
var optionalName: String? = "Hello" | |
/* | |
* # Understanding the Exclamation Mark (!) | |
* | |
* There are various places you might come across an exclamation mark in Swift code. | |
* The following examples are meant to capture the major types of use cases for the | |
* exclamation mark operator that can cause confusion when first learning Swift. | |
*/ | |
let possibleString: String? = "An optional string." | |
let forcedString: String = possibleString! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment