Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // class work answer:
- func getStudentInfo(students:[String:Double])->(avg:Double, best:[String], failed: [String]){
- let FAIL_GRADE:Double = 60
- var sum:Double = 0
- var max:Double = 0
- var myBest:[String] = []
- var myFailed:[String] = []
- for grade in students.values {
- if max < grade {
- max = grade
- }
- // max = max < grade ? grade : max // - the same thing in a single line
- }
- for (name,grade) in students{
- sum += grade
- if grade == max {
- myBest.append(name)
- }
- if grade < FAIL_GRADE {
- myFailed.append(name)
- }
- }
- let myAvg = sum / Double(students.count)
- return (avg: myAvg, best: myBest, failed: myFailed)
- }
- let myStudents = ["Yosi":70.0, "Avi": 49.0, "Barak": 70.0, "Mark":57.0, "David":65.0]
- let (avg, best, failed) = getStudentInfo(students: myStudents)
- print("avg: \(avg)")
- print("best: \(best)")
- print("failed: \(failed)")
- //-------------------------------------------------------------------------------------------------------------------
- //class, struct, protocol, enum, extension:
- //: Playground - noun: a place where people can play
- class Man{
- var name:String = "Tzahi"
- var age:Int = 32
- var saying:String = "I'm skipping class"
- func saySomething(){
- print("\(name) says \"\(saying)\"")
- }
- }
- var tzahi = Man()
- tzahi.saySomething()
- tzahi.name = "Ben"
- print(tzahi.name)
- class Person{
- var name:String
- var saying:String
- init(name:String, saying:String){ // init - initializer (like constructor in java)
- self.name = name
- self.saying = saying
- }
- func saySomething(){
- print("\(name) says \"\(saying)\"")
- }
- }
- var feras = Person(name: "Feras", saying:"HAFSAKA!!!!!")
- feras.saySomething()
- class Human{
- var name:String
- var saying:String
- init(name:String, saying:String){
- self.name = name
- self.saying = saying
- }
- init(name:String){ // overloading initializers
- self.name = name
- self.saying = "we want a break!"
- }
- func saySomething(){
- print("\(name) says \"\(saying)\"")
- }
- func saySomething(somethingToSay:String){ // oveloading methods
- print("\(name) says \"\(somethingToSay)\"")
- }
- }
- var odai = Human(name:"Odai")
- odai.saySomething(somethingToSay:"we already had a break")
- class HouseKey{
- var bumps:Int
- var owner:Human? // composition
- init(bumps:Int, owner:Human?) {
- self.bumps = bumps
- self.owner = owner
- }
- }
- let lostKey = HouseKey(bumps: 30, owner: nil)
- lostKey.owner?.name // will get us nil
- lostKey.owner = Human(name: "Ziv")
- lostKey.owner?.saySomething(somethingToSay: "I found my key")
- // inheritance and overriding
- class Animal{
- var name:String
- init(name:String){
- self.name = name
- }
- func makeSound(){
- print("\(name) makes some noise")
- }
- }
- class Cat : Animal { // like Cat extends Animal in java
- var clawLen:Int
- init(name:String, clawLen:Int){ // using the super class' initializer
- self.clawLen = clawLen // give the new property a value before calling super.init
- super.init(name: name)
- }
- override func makeSound() { // overriding a method from the super class - we must use the override keyword
- print("\(name) says \"meow\"")
- }
- }
- let animal = Animal(name:"Tiger")
- animal.makeSound()
- let cat = Cat(name: "mitsi", clawLen: 3)
- cat.makeSound()
- // polymorphism
- let cat2:Animal = Cat(name: "mitsi2", clawLen: 3)
- cat2.makeSound() // will use Cat's makeSound
- // protocols (like interfaces in java)
- class MyPrintable: CustomStringConvertible{ // CustomStringConvertible gives us the ability to add something similar to toString() from java. we need to use the description property
- var name = "the name"
- var age = 30
- var description: String { // like toString() in java
- return "\(name) is \(age) years old"
- }
- }
- let printable = MyPrintable()
- print(printable)
- protocol NoiseMaker{
- func makeNoise()
- }
- class Dog: Animal, NoiseMaker { // the inheritance must be the first in list
- // in java this would be: Dog extends Animal implements NoiseMaker
- func makeNoise() {
- makeSound()
- print("made sound from Dog")
- }
- }
- let dog = Dog(name: "Spot")
- dog.makeNoise()
- class CellPhone :NoiseMaker{
- var os:String = "iOS"
- func makeNoise() {
- print("Ring Ring")
- }
- }
- let myPhone = CellPhone()
- myPhone.makeNoise()
- let noiseMakers:[NoiseMaker] = [Dog(name:"spike"), CellPhone()]
- for noiseMaker in noiseMakers {
- if noiseMaker is Dog { // the is keyword is like instanceof in java - checks if the instance type is of the specified type
- print("\((noiseMaker as! Dog).name)") // force cast noiseMaker to Dog (as! - force cast)
- }
- print("\((noiseMaker as? CellPhone)?.os)") // safe cast noiseMaker to CellPhone (as? - safe cast, if we cannot cast the we get nil but NOT and error)
- noiseMaker.makeNoise()
- }
- // example of as without ! or ?
- let theDog = Dog(name: "the dog")
- theDog as Animal
- // struct vs class
- class MyClass{
- var name:String
- init(name:String) {
- self.name = name
- }
- func printSomething(){
- print("printed from MyClass")
- }
- }
- struct MyStruct{
- var name:String
- // note that we dont' have the initializer
- func printSomething(){
- print("printed from MyStruct")
- }
- }
- let myClass = MyClass(name: "myClass")
- let myStruct = MyStruct(name: "myStuct")
- myClass.printSomething()
- myStruct.printSomething()
- struct A{}
- class X{}
- protocol P{}
- //struct B:X{} // a struct cannot inherit from a class
- //struct B:A{} // a struct cannot inherit from another struct
- //class Y:A{} // a class cannot inherit from a struct
- struct B:P{} // a struct can implement a protocol
- class Y:P{} // a class and struct can both implement the same protocol
- class Baby: NoiseMaker{
- func makeNoise() {
- print("waaaaaaa")
- }
- }
- struct MotorBike: NoiseMaker{
- func makeNoise() {
- print("VROOOM")
- }
- }
- let moreNoisers:[NoiseMaker] = [Baby(), MotorBike()]
- for noiseMaker in moreNoisers{
- noiseMaker.makeNoise()
- }
- // computed properies
- class Rect{
- var side1:Int
- var side2:Int
- init(side1:Int, side2:Int) {
- self.side1 = side1
- self.side2 = side2
- }
- func getArea()->Int{
- return side1*side2
- }
- var area:Int{
- return side1*side2 // if none of get, set, didSet, willSet are written then get is used
- }
- private var _color = "white"
- var color:String{
- get{
- return _color
- }
- set{
- self._color = newValue // newValue is the value at the other side of the assignment operator. for instance: myRect.color = "blue" . "blue" is newVlaue
- }
- }
- }
- let myRect = Rect(side1: 3, side2: 5)
- print("the rectangle's area is \(myRect.area)")
- print("myRect's color is: \(myRect.color)")
- myRect.color = "red"
- print("myRect's color is now: \(myRect.color)")
- class Circle{
- var color:String {
- willSet{
- self.radius = 0
- }
- }
- var radius:Int {
- didSet{
- self.circumference = 2.0 * Double.pi * Double(self.radius) // calculate the circumference according to the new value of radius
- }
- }
- private(set) var circumference:Double// the value of circumference depends entirely on the value of radius
- init(radius:Int){
- self.color = "blue"
- self.radius = radius
- self.circumference = 2.0 * Double.pi * Double(self.radius)
- }
- }
- let circle = Circle(radius: 5)
- circle.radius = 5
- print("the circle's circumference is: \(circle.circumference)")
- circle.color = "yellow"
- print("the circle's radius after changing the color is: \(circle.radius)")
- // enum
- enum Direction{
- case north, south, east, west
- /* // another way fo writing this:
- case north
- case south
- case east
- case west
- */
- }
- let dir:Direction = .north
- switch(dir){
- case .north:
- print("in the north")
- case .south:
- print("in the south")
- case .east:
- print("in the east")
- case .west:
- print("in the west")
- }
- enum Element:CustomStringConvertible{ // an enum can implement a protocol
- case earth, water, fire, air
- var description: String { // enum can have members (for instance computed properties like description)
- switch self{ // switch on self to determine which enum case we are
- case .earth:
- return "earth"
- case .fire:
- return "fire"
- case .water:
- return "water"
- case .air:
- return "air"
- }
- }
- func getSideEffect()->String{
- switch self{
- case .earth:
- return "got dirty"
- case .fire:
- return "singed hair"
- case .water:
- return "all wet"
- case .air:
- return "hat got blown away"
- }
- }
- }
- let elem:Element = .fire
- print("the element is: \(elem)")
- print("the element' side effect is: \(elem.getSideEffect())")
- enum Stock:CustomStringConvertible{
- case buy(Int,String), sell(Int), stay
- var description: String{
- switch self{ // switch on self to determine which enum case we are
- case .buy(let amount, let company):
- return "bought \(amount) of \(company) stock"
- case .sell(let amount):
- return "sold \(amount)"
- case .stay:
- return "didn't change a thing"
- }
- }
- }
- let myStock:Stock = .buy(4,"AAPL")
- print("my stock transaction is: \(myStock)")
- switch myStock{
- case .buy(_, let company) where company=="AAPL": // add an additional condition to the case
- print("bought some AAPL")
- default:
- print("some stock transaction")
- }
- // extensions
- extension String{
- // we CANNOT add stored properties in an extension
- var isInt:Bool{
- return Int(self) != nil
- }
- var toInt:Int{
- return Int(self) ?? 0 // ?? gives a defualt value if the left hand side is n nil
- }
- }
- let st = "23"
- print("hello".isInt)
- print(st.toInt)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement