Skip to content

Instantly share code, notes, and snippets.

@coryalder
Created July 20, 2015 16:47
Show Gist options
  • Save coryalder/fbfcbc1ba183d9bb3a05 to your computer and use it in GitHub Desktop.
Save coryalder/fbfcbc1ba183d9bb3a05 to your computer and use it in GitHub Desktop.
a quick intro to some of the language features of swift
//: Playground - noun: a place where people can play
import Cocoa
// basic strings
var str: String = "Hello,"
let helloWorld = str + " world"
str
// string interpolation
// var, let, type inferrence
var hoursWorked = 35 // type inferred to be Int
let hourlyRate: Float = 25.0 // type specified as Float
let someNumber = 10 // type inferred to be Int
var str2 = "The value of someNumber is \(someNumber * 2)" // string interpolation
print(str2)
//let variable1: String = "some string \(1.09*12) \(231*12.0)"
// an array of strings
var instructors = ["cory", "ken", "ian"] // type inferred to be [String], or Array<String> to put it another way.
//let value = instructors.last as! String // get the last value in the array, and cast it to a String. Cast is not needed if the array is of type [String], only if it's of a less specific type, like [NSObject].
// array of arrays
var groupsOfStudents = [["Cory", "Ken"], ["Alex", "Arsalan"]] // type inferred to be [[String]] (or: Array<Array<String>>, to put it another way)
groupsOfStudents.append(["Cory"]) // append an array with one string object to the groupsOfStudents array.
groupsOfStudents
// optional string
let optionalString: String? = "a string"
print(optionalString)
// Creating new objects of various types.
let students = [String]() // a new empty array of strings
let countOfStudents = Int() // new int, with whatever it's default value is (0, duh)
// Dictionaries
var salaries = ["Jane" : 16000, "Joe" : 5000] // inferred type of...
salaries["Sally"] = 12 // set a new value in that dictionary
salaries
// Converting between an Int and a Double.
let someDouble = 10.0
let someInt = 1
let result = someDouble * Double(someInt) // without this,it's a compile error, because there is no "*" function that takes a Double and an Int as its parameters
var something: String
//print(something) // won't work, because something has never been set, and is not optional.
// find the index of a
func findIndexOf(value: String, set: [String]) -> Int? {
let f = find(set, value)
return f
}
// instructors is defined above
//var instructors = ["cory", "ken", "ian"]
var myIndex = findIndexOf("cory", instructors)
// findIndexOf _must_ return an optional, because "cory" may not appear in the instructors array. There is no way to know ahead of time.
print("Index is \(myIndex)")
//print("Hi, I’m \(instructors[myIndex])") // cannot pass an Int? as an array index
// unwrapping myIndex (an Int?) into index (an Int)
if let index = myIndex {
print("Index is \(index)")
print("Hi, I’m \(instructors[index])")
} else {
print("no index returned")
}
// unwrapping two things in one if
var maybeDouble: Double? = 1.0
if let index = myIndex, let count = maybeDouble {
print("Hi, I’m \(index), \(count)")
} else {
print("no index returned")
}
// force-unwrapping. HERE THERE BE DRAGONS!
if myIndex != nil {
print(myIndex!)
}
// e.g. these dragons:
//print(myIndex!)
// Functions
// simple no input no output function:
func printMyName() {
print("my name")
}
printMyName()
// one input, no output function:
func printAnyName(nameString: String) {
print("any name is \(nameString)")
}
printAnyName("cory")
// two input, no output function
func printAnyFullName(nameString: String, count: Int) {
for i in 0..<count {
print("any name is \(nameString)")
}
}
printAnyFullName("Cory", 10)
// Closures
// Closures are unnamed functions
// functions are named closures
let numbers = [1,2,3,4,5,6]
numbers.map({ (number: Int) -> Int in
return number * 3
})
// with inferred types, and trailing-closure syntax
numbers.map {
number in
return number * 3
}
// the very simplist syntax for this map operation
numbers.map { $0 * 3 }
// Classes
class Box {
var height: Int = 10
var width: Int = 10 {
didSet {
let i = 1
print("we just set our width")
}
}
}
var myBox = Box()
myBox.width = 20
// same thing again, but with a struct:
struct ValueBox {
var height: Int = 10
var width: Int = 10 {
// do this block of code when the width property is set
didSet {
let i = 1
print("we just set our width")
}
}
}
var myValueBox = ValueBox() // a box with default values
myValueBox = ValueBox(height: 20, width: 15) // with structs we get an initializer with all of our properties by default. With classes we have to write our own.
myValueBox.width = 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment