Skip to content

Instantly share code, notes, and snippets.

@mackhowell
Created September 23, 2015 21:14
Show Gist options
  • Save mackhowell/136ce4ec8713bf68b025 to your computer and use it in GitHub Desktop.
Save mackhowell/136ce4ec8713bf68b025 to your computer and use it in GitHub Desktop.
tuples
//: Playground - noun: a place where people can play
import UIKit
// ARRAYS
// many ways to mak arrays
var array1: Array<String>
var array2: [String]
var array3 = ["apple", "pear"]
var a = [String](count: 5, repeatedValue: "mack")
//getting and setting vals
array3[1]
array3[1] = "dog"
array3
//you can merge immutable arrays
let aa = [1,1,1]
let bb = [2,2,2]
let cc = aa+bb
//other operations (to be used with mutalbe arrays)
var thisarry = ["this", "array"]
thisarry.append("is")
thisarry.count
thisarry.insert("cool", atIndex: 3)
//convenient methods
thisarry.isEmpty
// DICTIONARIES
// declaration is the same as arrays, but you need to specify the type for both keys and values
var dic1: Dictionary<String, Int>
var dic2: [String: Int]
var dic3 = ["Apple": 3, "pear": 2, "peach": 1]
//getting a value
let val = dic3["Apple"]
// other standard lib goodies
dic3.removeValueForKey("pear")
dic3
dic3 = [:] // nil the dictionary
// TUPLES
// they're diff b/c vals don't have to be of the same type!
var currency = ("EUR", 500.0)
var time = (NSDate(), "time stamp")
var email = ("mack howell", "[email protected]")
// Accessors
var rate = currency.1
var mess = time.1
var name = email.0
// you can also name the values!!!
var person = (name: "mack", hair: "brown", age: 27)
person.hair
// or instantiating w/ param names, and `type inference...
var response = (statusCode: 200, statusText: "OK", hasBody: true)
// decomposition i.e. assigning values to the tuple's values
let (currencyName, amount) = currency
// EMPTY tuple
var emptyTuple: ()
// swift has a typealias for empty tuple called Void
var emptyTuple2: Void
// ONE tuple
var test: Int
var test2: (Int)
var test3: (((((((Int)))))))
// ALL INTS!!!!
// one tuple is special because it just equals itself and does not return a tuple
var mapping: (Int -> Int)
// makes it so we can return the type here, it doesn't have to implicitly BE a tuple
var n = 5
var sum = (n * (n + 1)) / 2 //also makes it so we can do math. here sum knows to return an int, not a tuple.
// USES to use tuples
//var one = 1
//var two = 2
//var three = 3
// becomes
var (one,two,three) = (1, 2, 3)
print(one)
// iterating arrays or dics
let dictionaryyy = ["one": "two", "two":"three"]
for (key, value) in dic3 {
print(key)
}
// SWITCH statuments
var point = (x: 5, y: 6)
switch point {
case (0,0):
print("origin")
case (_,0): // WILDCARD operator
print("on x axis")
case (0,_):
print("on y axis")
case (-1...1, -1...1):
print("near origin")
case let (x, y) where x == -y: // WHERE statement
print("On diagonal")
default: // could also be case _: (wildcard case
()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment