2014-06-04 07:50:17 +00:00
---
language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
2014-08-24 03:48:10 +00:00
- ["Christopher Bess", "http://github.com/cbess"]
2014-06-04 07:50:17 +00:00
filename: learnswift.swift
---
Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta.
See also Apple's [getting started guide ](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html ), which has a complete tutorial on Swift.
```js
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Basics
2014-06-04 20:22:01 +00:00
//
2014-06-04 07:50:17 +00:00
println("Hello, world")
2014-08-24 03:48:10 +00:00
2014-06-04 07:50:17 +00:00
var myVariable = 42
2014-08-24 03:48:10 +00:00
//let fƒ∆ = "value" // unicode in variable names
2014-06-04 07:50:17 +00:00
let myConstant = 3.1415926
2014-08-24 03:48:10 +00:00
let convenience = "keyword" // contextual variable name
let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon
let `class` = "keyword" // backticks allow keywords to be used as variable names
2014-06-04 07:50:17 +00:00
let explicitDouble: Double = 70
2014-08-24 03:48:10 +00:00
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
2014-06-04 07:50:17 +00:00
let label = "some text " + String(myVariable) // Casting
let piText = "Pi = \(myConstant)" // String interpolation
var optionalString: String? = "optional" // Can be nil
optionalString = nil
2014-08-24 03:48:10 +00:00
/*
Comment here
/*
Nested comment here
*/
*/
2014-06-04 07:50:17 +00:00
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Collections
2014-06-04 20:22:01 +00:00
//
2014-06-04 07:50:17 +00:00
// Array
var shoppingList = ["catfish", "water", "lemons"]
shoppingList[1] = "bottle of water"
2014-07-16 10:20:57 +00:00
let emptyArray = [String]()
2014-06-04 07:50:17 +00:00
// Dictionary
var occupations = [
2014-08-24 03:48:10 +00:00
"Malcolm": "Captain",
"kaylee": "Mechanic"
2014-06-04 07:50:17 +00:00
]
occupations["Jayne"] = "Public Relations"
let emptyDictionary = Dictionary< String , Float > ()
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Control Flow
2014-06-04 20:22:01 +00:00
//
2014-06-04 07:50:17 +00:00
// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
2014-08-24 03:48:10 +00:00
if value == 1 {
println("One!")
} else {
println("Not one!")
}
2014-06-04 07:50:17 +00:00
}
// for loop (dictionary)
2014-08-24 03:48:10 +00:00
var dict = ["one": 1, "two": 2]
2014-06-04 07:50:17 +00:00
for (key, value) in dict {
2014-08-24 03:48:10 +00:00
println("\(key): \(value)")
2014-06-04 07:50:17 +00:00
}
// for loop (range)
for i in -1...1 { // [-1, 0, 1]
2014-08-24 03:48:10 +00:00
println(i)
2014-06-04 07:50:17 +00:00
}
2014-07-16 10:20:57 +00:00
// use ..< to exclude the last number
2014-06-04 07:50:17 +00:00
// while loop
var i = 1
while i < 1000 {
2014-08-24 03:48:10 +00:00
i *= 2
2014-06-04 07:50:17 +00:00
}
// do-while loop
do {
2014-08-24 03:48:10 +00:00
println("hello")
2014-06-04 07:50:17 +00:00
} while 1 == 2
// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
2014-08-24 03:48:10 +00:00
let vegetableComment = "Add some raisins and make ants on a log."
2014-06-04 07:50:17 +00:00
case "cucumber", "watercress":
2014-08-24 03:48:10 +00:00
let vegetableComment = "That would make a good tea sandwich."
2014-06-04 07:50:17 +00:00
case let x where x.hasSuffix("pepper"):
2014-08-24 03:48:10 +00:00
let vegetableComment = "Is it a spicy \(x)?"
2014-06-04 07:50:17 +00:00
default: // required (in order to cover all possible input)
2014-08-24 03:48:10 +00:00
let vegetableComment = "Everything tastes good in soup."
2014-06-04 07:50:17 +00:00
}
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Functions
2014-06-04 20:22:01 +00:00
//
// Functions are a first-class type, meaning they can be nested
// in functions and can be passed around
2014-06-04 07:50:17 +00:00
// Function
func greet(name: String, day: String) -> String {
2014-08-24 03:48:10 +00:00
return "Hello \(name), today is \(day)."
2014-06-04 07:50:17 +00:00
}
greet("Bob", "Tuesday")
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
2014-08-24 03:48:10 +00:00
return (3.59, 3.69, 3.79)
2014-06-04 07:50:17 +00:00
}
2014-08-24 03:48:10 +00:00
// Variadic Args
2014-06-04 07:50:17 +00:00
func setup(numbers: Int...) {}
// Passing and returning functions
func makeIncrementer() -> (Int -> Int) {
2014-08-24 03:48:10 +00:00
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
2014-06-04 07:50:17 +00:00
}
var increment = makeIncrementer()
increment(7)
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Closures
2014-06-04 20:22:01 +00:00
//
2014-07-16 10:20:57 +00:00
var numbers = [1, 2, 6]
2014-06-04 20:22:01 +00:00
// Functions are special case closures ({})
2014-06-04 07:50:17 +00:00
// Closure example.
// `->` separates the arguments and return type
// `in` separates the closure header from the closure body
numbers.map({
2014-08-24 03:48:10 +00:00
(number: Int) -> Int in
let result = 3 * number
return result
})
2014-06-04 07:50:17 +00:00
// When the type is known, like above, we can do this
numbers = numbers.map({ number in 3 * number })
2014-08-24 03:48:10 +00:00
// Or even this
2014-07-16 10:20:57 +00:00
//numbers = numbers.map({ $0 * 3 })
2014-06-04 07:50:17 +00:00
print(numbers) // [3, 6, 18]
2014-08-24 03:48:10 +00:00
// Trailing closure
numbers = sorted(numbers) { $0 > $1 }
print(numbers) // [18, 6, 3]
// Super shorthand, since the < operator infers the types
numbers = sorted(numbers, < )
print(numbers) // [3, 6, 18]
2014-06-04 07:50:17 +00:00
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Classes
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
class Shape {
func getArea() -> Int {
return 0;
}
}
2014-06-04 20:22:01 +00:00
// All methods and properties of a class are public.
// If you just need to store data in a
// structured object, you should use a `struct`
2014-06-04 07:50:17 +00:00
2014-06-05 14:49:42 +00:00
// A simple class `Square` extends `Shape`
2014-06-04 07:50:17 +00:00
class Rect: Shape {
2014-08-24 03:48:10 +00:00
var sideLength: Int = 1
// Custom getter and setter property
var perimeter: Int {
get {
return 4 * sideLength
}
set {
sideLength = newValue / 4
}
2014-06-04 07:50:17 +00:00
}
2014-08-24 03:48:10 +00:00
// If you don't need a custom getter and setter,
// but still want to run code before and after getting or setting
// a property, you can use `willSet` and `didSet`
var identifier: String = "defaultID" {
willSet(someIdentifier) {
print(someIdentifier)
}
2014-06-04 07:50:17 +00:00
}
2014-08-24 03:48:10 +00:00
init(sideLength: Int) {
super.init()
self.sideLength = sideLength
}
func shrink() {
if sideLength > 0 {
--sideLength
}
2014-06-04 07:50:17 +00:00
}
2014-08-24 03:48:10 +00:00
override func getArea() -> Int {
return sideLength * sideLength
}
}
2014-06-04 07:50:17 +00:00
2014-08-24 03:48:10 +00:00
class Square: Rect {
convenience init() {
self.init(sideLength: 5)
}
2014-06-04 07:50:17 +00:00
}
2014-08-24 03:48:10 +00:00
var mySquare = Square()
2014-06-04 07:50:17 +00:00
print(mySquare.getArea()) // 25
mySquare.shrink()
print(mySquare.sideLength) // 4
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Enums
2014-06-04 20:22:01 +00:00
//
// Enums can optionally be of a specific type or on their own.
// They can contain methods like classes.
2014-06-04 07:50:17 +00:00
enum Suit {
2014-08-24 03:48:10 +00:00
case Spades, Hearts, Diamonds, Clubs
func getIcon() -> String {
switch self {
case .Spades: return "♤"
case .Hearts: return "♡"
case .Diamonds: return "♢"
case .Clubs: return "♧"
}
2014-06-04 07:50:17 +00:00
}
}
2014-06-04 20:22:01 +00:00
//
2014-08-24 03:48:10 +00:00
// MARK: Other
2014-06-04 20:22:01 +00:00
//
2014-06-04 07:50:17 +00:00
2014-06-04 20:22:01 +00:00
// `protocol` : Similar to Java interfaces.
2014-08-24 03:48:10 +00:00
protocol ShapeGenerator {
func buildShape() -> Shape
}
// `extension` s: Add extra functionality to an already existing type
extension Square: Printable {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
}
println("Square: \(mySquare)")
2014-06-04 20:22:01 +00:00
// Generics: Similar to Java. Use the `where` keyword to specify the
// requirements of the generics.
2014-06-04 07:50:17 +00:00
2014-08-24 03:48:10 +00:00
func findIndex< T: Equatable > (array: [T], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
2014-07-16 10:20:57 +00:00
```