Skip to content

Instantly share code, notes, and snippets.

@ccabanero
Created June 3, 2014 13:15
Show Gist options
  • Save ccabanero/e4b95096916b2ec4c7aa to your computer and use it in GitHub Desktop.
Save ccabanero/e4b95096916b2ec4c7aa to your computer and use it in GitHub Desktop.
Swift Reference
import UIKit
// variable
var myVariable = 3
myVariable += 1
//------------------------------------------
/*
// constant
let myConstant = 4
myConstant
*/
//------------------------------------------
/*
// declaring variable with type
var myVariable:Double
myVariable = 2
myVariable + 1
myVariable + 3.3
var myFloat:Float
myFloat = 4
myFloat = 3.2
*/
//------------------------------------------
/*
// concatenating types
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
*/
/*
// alternatives to concatenating
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let orangeSummary = "I have \(oranges) oranges."
let fruitSummary = "I have \(oranges + apples) fruit."
*/
//------------------------------------------
/*
// array
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1]
*/
//------------------------------------------
/*
// dictionary
var occupations = [
"malcolm":"captain",
"kaylee":"mechanic"
]
occupations["malcolm"]
occupations["jayne"] = "humarn resources"
occupations["jayne"]
*/
//------------------------------------------
/*
// if then
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore
*/
/*
// if then with optionals
var optionalString: String? = "Hello"
optionalString == nil;
var optionalName:String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
*/
//------------------------------------------
/*
// switch with string literals and an expression in the case
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and makme ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
*/
//------------------------------------------
/*
// iterate dictionary
let interestingNumbers = [
"Prime":[2,3,5,7,11,13],
"Fibonacci":[1,1,2,3,5,8],
"Square":[1,4,9,16,25]
]
var largest = 0
for(kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
*/
//------------------------------------------
/*
// while loop
var n = 2
while n < 100 {
n = n * 2
}
n
// do while loop
var m = 2
do {
m = m * 2
} while m < 100
m
// for loop
var firstForLoop = 0
for i in 0..3 {
firstForLoop += 1
}
firstForLoop
var amount = 5
let length = 3
for i in 0..length {
amount *= 3
}
amount
*/
//------------------------------------------
/*
// functions with single return value
func greet(name:String, day:String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Clint", "Monday")
*/
//------------------------------------------
/*
// function with multiple return values
func getGasPrices() -> (Double, Double, Double) {
return (3.5, 2.5, 1.1)
}
getGasPrices()
// function with multiple return values of different types
func returnStuff() -> (Double, Integer) {
return (3.5, 2)
}
returnStuff()
*/
//------------------------------------------
/*
// function with variable number of arguments
func sumOf(numbers:Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(1, 1)
sumOf(1, 2, 3)
*/
//------------------------------------------
/*
// nested functions
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
*/
//------------------------------------------
/*
// functions returning functions
func makeIncrement() -> (Int -> Int) {
func addOne(number:Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrement()
increment(7)
*/
//------------------------------------------
/*
// functions passed as an argument to another function
func hasAnyMatches(list:Int[], condition:Int -> Bool) -> Bool{
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)
*/
//------------------------------------------
/*
// closure without a name
var numbers = [20, 19, 7, 12]
numbers.map({
(number:Int) -> Int in
let result = 3 * number
return result
})
*/
//------------------------------------------
/*
// simple class
class NamedShape {
var numberOfSides:Int = 0
var name:String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
// instantiate object and use
var shape = NamedShape(name: "RoundThing")
shape.numberOfSides = 3
shape.simpleDescription()
//------------------------------------------
// class inheritance
class Square:NamedShape {
var sideLength:Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength
super.init(name:name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)"
}
}
// instantiate object and use
let test = Square(sideLength:5.2,name:"my test square")
test.area()
test.simpleDescription()
//------------------------------------------
// class inheritance
class Circle:NamedShape {
var radius:Double
init(radius:Double, name:String) {
self.radius = radius
super.init(name:name)
numberOfSides = 3
}
func area() -> Double {
return 3.14159265359 * radius * radius
}
override func simpleDescription() -> String {
return "A Circle with radius \(radius)."
}
}
// instantiate object and use
let myCircle = Circle(radius: 3.2, name: "ClintCircle")
myCircle.area()
myCircle.simpleDescription()
//------------------------------------------
// property getters and setters
class EquilateralTriangle:NamedShape {
var sideLength:Double = 0.0
init(sideLength:Double, name:String) {
self.sideLength = sideLength
super.init(name:name)
numberOfSides = 3
}
var perimeter:Double {
get{
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
// instantiate object and use
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
//------------------------------------------
// composition and willset and didSet
class TriangleAndSquare {
var triangle:EquilateralTriangle {
willSet {
triangle.sideLength = newValue.sideLength
}
}
var square:Square {
willSet {
square.sideLength = newValue.sideLength
}
}
init(size:Double, name:String) {
square = Square(sideLength:size, name:name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength:50, name:"larger square")
triangleAndSquare.triangle.sideLength
*/
//------------------------------------------
// protocol
protocol ExampleProtocol {
var simpleDescription:String { get }
mutating func adjust()
}
// class adopting the protocol
class SimpleClass:ExampleProtocol {
var simpleDescription:String = "A very simple class."
var anotherProperty:Int = 98199
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
// use
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment