// My first (and only) swift program // compile: swiftc prog1.swift, produces executable prog1 import Glibc // in case we need it let x = 1 func f() -> Int { return x } func g() { let x = 2 print(x) // prints 2 print(f()) // prints 1, good } g() ///// testing for closure (already know it should work) func makeaccumulator(x:Int) -> (Int)->Int { // can we use x without declaring another var? no, x is not mutable var y = x; // the closure variable func a(z:Int)->Int { y+=z; return y; } return a } let a1 = makeaccumulator(x:0) let a2 = makeaccumulator(x:0) print(a1(2)) print(a1(2)) print(a1(2)) print(a2(2)) ///// class AA { var xx = 1 func f() { print("AA.f",xx) } } class BB : AA { // can't override xx: like Java override func f() { print("BB.f "+String(xx)) } func g()->Int { return 0 } } var n:AA = AA(); n.f() //let nb = n as! BB; nb.g(); // downcast : runtime error as expected // n = 4 // compiler error - thank god n = BB() n.f() // dynamic dispatch confirmed, prints BB.f 1 let nb = n as! BB; print(nb.g()); // downcast /////////////// extensions, not BS like C#, hopefully extension AA { // var yy = 2 no stored properties in extensions func g() { print("AA.g",xx) } } var m:AA m = AA() m.g() /*** extension BB { override func g() { print("BB.g") } } // Swift 4.0: 'error: declarations in extensions cannot override yet' // YET??? So disappointing!!!! ********** */ // one more chance, how about extending protocols: protocol P1 // equivalent to interface { func f() } class AP : P1 { func f() { print("AA.f") } } class BP : P1 { func f() { print("BB.f") } } ////////////////// extending the protocol (just default method) extension P1 { //func g2() // not allowed without definition func g() { print("BORING!"); } } extension AP { func g() { print("A.g"); } } extension BP { func g() { print("B.g"); } } var q:P1 = AP() // different static and dynamic types var r:P1 = BP() for _ in 0..<10 { q.g(); r.g() // BORING indeed }