Skip to content

Instantly share code, notes, and snippets.

@pawurb
Last active August 29, 2015 14:02
Show Gist options
  • Save pawurb/378c26d165b5c41747ba to your computer and use it in GitHub Desktop.
Save pawurb/378c26d165b5c41747ba to your computer and use it in GitHub Desktop.
trying out swift
// Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
var dictionary = [1 : "1",2 : "2" ,3 : "3"]
for (a , b) in dictionary {
println(String(a) + b)
}
var array = [1,2,3,4, "4"]
String(1)
array[1]
dictionary[2]
let dupa = str + String(99)
println(dupa)
var hello = "world"
hello = String(1)
for a in 0...4 {
println(a)
}
func hello(name: String, times: Int) -> String {
for a in 0..times {
println("Hello \(name) for \(a+1) times.")
}
return "done"
}
func variousValues() -> (Double, Double, Double){
return (3,3,3)
}
hello("world", 5);
println(variousValues())
func returnFunc(multiplier: Int) -> (Int-> Int) {
func innerFunc(number: Int) -> Int {
return number * multiplier
}
return innerFunc
}
var integerFunc = returnFunc(5)
String(integerFunc(3))
func hasGoodNumber(list: Int[], verifier: Int -> Bool) -> Bool {
for item in list {
if verifier(item){
return true
}
}
return false
}
func oddFinder (number: Int) -> Bool {
if(number % 2 == 0){
return false
} else {
return true
}
}
let funcVariable = oddFinder
//function as a parameter
hasGoodNumber([2,2,2,2], oddFinder)
hasGoodNumber([2,2,2,1], funcVariable)
//closuer
[1,2,3,4].map({ (number: Int) -> Int in
let result = number * number
return result
})
let triple = [1,2,3,4].map({number in number * number * number})
triple
let dupaFinder = { (word: String) -> Bool in
return word == "dupa"
}
["dupa", "dupa2", "niedupa"].filter(dupaFinder)
let sorted = sort([1,4,5,3,7,4,1])
sorted
sorted.reverse()
class Person {
var name: String
init(name: String) {
self.name = name
}
func sayHello() -> String {
return "Hello my name is \(name)"
}
}
class Slave : Person {
var owner: String
override func sayHello() -> String {
return super.sayHello() + " Sir"
}
init(name: String, owner: String) {
self.owner = owner
super.init(name: name)
}
func workHard() -> String {
return "I work hard for \(self.owner)"
}
}
let Tom = Person(name: "Tom")
Tom.sayHello()
let John = Slave(name: "John", owner: "Tom")
John.sayHello()
John.workHard()
protocol FriendlyNumber {
func greet()
}
extension Int {
func greet() -> String {
return "Hello, I am an Integer and my value is \(self)"
}
func times(task: () ->() ) {
for i in 0..self {
task()
}
}
}
1.greet()
567.greet()
5.times {
println("hello world")
}
var empty: Int? = nil
empty = 6
println(empty)
println(empty!) //unwrapping
if empty {
let value = empty! //unwrappping
value
}
//shorthand
if let value = empty {
value
}
let possibleString: String? = "An optional string."
println(possibleString) //no need to unwrap?
var assumedString: String! = "An implicitly unwrapped optional string."
assumedString = nil
println(assumedString)
let age = 16
assert(age >= 15, "Too young") //will raise an error
age < 15 ? "assertion not work good" : "assertion reliable"
let (a,b,c) = (1,2.22, "dupa") //decomposing tuple
a
b
c
var valueExist: String?
valueExist = nil
var strContainer: String
/* = operator does not return a value
if strContainer = valueExist {
println("not possible")
}
*/
var one = 1
if "lala" {
println("string is true -> 🐶")
} else {
println("zero is false")
}
countElements("dupa")
var char: Character = "1"
char = "l"
"dupa".uppercaseString
var nums: Int[] = [1,2,3,4]
var words = ["one", "two", "three"] //implicit typing(??)
nums.append(5)
nums
//nums.append("six")
nums[2]
nums.insert(6, atIndex: 0)
nums
nums.removeAtIndex(2)
nums.removeLast() // pop!
for (index, item) in enumerate(words) {
println("\'\(item)\' at index: \(index)")
}
nums.count
var legs: Dictionary<String, Int> = ["goat" : 4, "snake" : 0, "spider" : 6]
//tuple to iterate the dictionary
for (species, numLegs) in legs {
println("\(species) has \(numLegs) legs")
}
//check if dictionary val exists
if let animal = legs["cat"] {
println("we counted the cats legs")
}
if let oldValue = legs.updateValue(4, forKey: "snake") {
println("The old leg value for snake was \(oldValue).")
}
for name in legs.keys { //dictionary to array
println(name)
}
var namesOfIntegers = [:]
//accessing tuple members
let point = (3,2)
point.0
point.1
() // empty tuple ~= Void
//functions with named parameters
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: ", ")
// Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
class Suspect {
class func classDescription() -> String {
return "we are suspected"
}
func _privateWannabee(){
println("am i private?")
}
var activity: String {
willSet(newActivity) {
println("He was \(activity) but now he is going to \(newActivity)")
}
didSet {
println("He was \(oldValue) but now he is \(activity)")
}
}
var description: String {
get {
return "he is \(activity)"
}
}
init(_ activity: String) {
self.activity = activity
}
convenience init() {
self.init("nothing")
}
func goTo(city: String, by: String, to: String) {
println("will do!")
}
func goTo(city: String, _ by: String, to: String) {
println("overloaded!")
}
deinit {
println("goodbye")
}
}
//inout lets you odify params inside func (pass by reference)
func genericSwapper<T>(inout a: T, inout b: T){
let tmp = a
a = b
b = tmp
}
var int1 = 1
var int2 = 2
genericSwapper(&int1, &int2)
int1
int2
var string1 = "one"
var string2 = "two"
genericSwapper(&string1, &string2)
string1
string2
var sus: Suspect? = Suspect("sleeping")
sus!.activity = "showering"
sus.description
sus!.goTo("kraków", by: "bus", to: "work")
sus!.goTo("kraków", "bus", to: "work")
sus!._privateWannabee()
sus = nil
func suspectFactory() {
var sus2 = Suspect()
}
suspectFactory()
Suspect.classDescription()
let PI = 3.14
var x = -PI * 2
while x < PI * 2 {
cos(x)
x += 0.2
}
//generic function with protocol conformance
func findIndex<T: Equatable>(array: T[], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
findIndex([0,1,2,3,4], 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment