Advertisement
Guest User

class, struct, protocol, enum, extension

a guest
Jul 15th, 2018
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 10.64 KB | None | 0 0
  1. // class work answer:
  2.  
  3. func getStudentInfo(students:[String:Double])->(avg:Double, best:[String], failed: [String]){
  4.    
  5.     let FAIL_GRADE:Double = 60
  6.    
  7.     var sum:Double = 0
  8.     var max:Double = 0
  9.     var myBest:[String] = []
  10.     var myFailed:[String] = []
  11.    
  12.     for grade in students.values {
  13.         if max < grade {
  14.             max = grade
  15.         }
  16.         // max = max < grade ? grade : max // - the same thing in a single line
  17.     }
  18.    
  19.     for (name,grade) in students{
  20.         sum += grade
  21.        
  22.         if grade == max {
  23.             myBest.append(name)
  24.         }
  25.        
  26.         if grade < FAIL_GRADE {
  27.             myFailed.append(name)
  28.         }
  29.     }
  30.    
  31.     let myAvg = sum / Double(students.count)
  32.    
  33.     return (avg: myAvg, best: myBest, failed: myFailed)
  34.    
  35. }
  36.  
  37. let myStudents = ["Yosi":70.0, "Avi": 49.0, "Barak": 70.0, "Mark":57.0, "David":65.0]
  38. let (avg, best, failed) = getStudentInfo(students: myStudents)
  39.  
  40. print("avg: \(avg)")
  41. print("best: \(best)")
  42. print("failed: \(failed)")
  43.  
  44.  
  45. //-------------------------------------------------------------------------------------------------------------------
  46. //class, struct, protocol, enum, extension:
  47.  
  48.  
  49.  
  50. //: Playground - noun: a place where people can play
  51.  
  52.  
  53. class Man{
  54.     var name:String = "Tzahi"
  55.     var age:Int = 32
  56.     var saying:String = "I'm skipping class"
  57.    
  58.     func saySomething(){
  59.         print("\(name) says \"\(saying)\"")
  60.     }
  61. }
  62.  
  63. var tzahi = Man()
  64. tzahi.saySomething()
  65. tzahi.name = "Ben"
  66. print(tzahi.name)
  67.  
  68. class Person{
  69.     var name:String
  70.     var saying:String
  71.    
  72.     init(name:String, saying:String){ // init - initializer (like constructor in java)
  73.         self.name = name
  74.         self.saying = saying
  75.     }
  76.    
  77.     func saySomething(){
  78.         print("\(name) says \"\(saying)\"")
  79.     }
  80. }
  81.  
  82. var feras = Person(name: "Feras", saying:"HAFSAKA!!!!!")
  83.  
  84. feras.saySomething()
  85.  
  86.  
  87. class Human{
  88.     var name:String
  89.     var saying:String
  90.    
  91.     init(name:String, saying:String){
  92.         self.name = name
  93.         self.saying = saying
  94.     }
  95.    
  96.     init(name:String){ // overloading initializers
  97.         self.name = name
  98.         self.saying = "we want a break!"
  99.     }
  100.    
  101.     func saySomething(){
  102.         print("\(name) says \"\(saying)\"")
  103.     }
  104.    
  105.     func saySomething(somethingToSay:String){ // oveloading methods
  106.         print("\(name) says \"\(somethingToSay)\"")
  107.     }
  108.    
  109.    
  110. }
  111.  
  112. var odai = Human(name:"Odai")
  113. odai.saySomething(somethingToSay:"we already had a break")
  114.  
  115.  
  116. class HouseKey{
  117.     var bumps:Int
  118.     var owner:Human? // composition
  119.    
  120.     init(bumps:Int, owner:Human?) {
  121.         self.bumps = bumps
  122.         self.owner = owner
  123.     }
  124. }
  125.  
  126. let lostKey = HouseKey(bumps: 30, owner: nil)
  127. lostKey.owner?.name // will get us nil
  128. lostKey.owner = Human(name: "Ziv")
  129. lostKey.owner?.saySomething(somethingToSay: "I found my key")
  130.  
  131.  
  132. // inheritance and overriding
  133.  
  134. class Animal{
  135.     var name:String
  136.    
  137.     init(name:String){
  138.         self.name = name
  139.     }
  140.    
  141.     func makeSound(){
  142.         print("\(name) makes some noise")
  143.     }
  144. }
  145.  
  146.  
  147. class Cat : Animal { // like Cat extends Animal in java
  148.    
  149.     var clawLen:Int
  150.    
  151.     init(name:String, clawLen:Int){ // using the super class' initializer
  152.         self.clawLen = clawLen // give the new property a value before calling super.init
  153.         super.init(name: name)
  154.     }
  155.    
  156.     override func makeSound() { // overriding a method from the super class -  we must use the override keyword
  157.         print("\(name) says \"meow\"")
  158.     }
  159. }
  160.  
  161. let animal = Animal(name:"Tiger")
  162. animal.makeSound()
  163. let cat = Cat(name: "mitsi", clawLen: 3)
  164. cat.makeSound()
  165.  
  166. // polymorphism
  167. let cat2:Animal = Cat(name: "mitsi2", clawLen: 3)
  168. cat2.makeSound() // will use Cat's makeSound
  169.  
  170.  
  171. // protocols (like interfaces in java)
  172.  
  173. class MyPrintable: CustomStringConvertible{ // CustomStringConvertible gives us the ability to add something similar to toString() from java. we need to use the description property
  174.     var name = "the name"
  175.     var age = 30
  176.    
  177.     var description: String { // like toString() in java
  178.         return "\(name) is \(age) years old"
  179.     }
  180.    
  181. }
  182.  
  183. let printable = MyPrintable()
  184. print(printable)
  185.  
  186.  
  187. protocol NoiseMaker{
  188.     func makeNoise()
  189. }
  190.  
  191. class Dog: Animal, NoiseMaker { // the inheritance must be the first in list
  192.     // in java this would be: Dog extends Animal implements NoiseMaker
  193.    
  194.    
  195.     func makeNoise() {
  196.         makeSound()
  197.         print("made sound from Dog")
  198.     }
  199.    
  200. }
  201.  
  202. let dog = Dog(name: "Spot")
  203. dog.makeNoise()
  204.  
  205.  
  206. class CellPhone :NoiseMaker{
  207.    
  208.     var os:String = "iOS"
  209.    
  210.     func makeNoise() {
  211.         print("Ring Ring")
  212.     }
  213. }
  214.  
  215. let myPhone = CellPhone()
  216. myPhone.makeNoise()
  217.  
  218. let noiseMakers:[NoiseMaker] = [Dog(name:"spike"), CellPhone()]
  219. for noiseMaker in noiseMakers {
  220.     if noiseMaker is Dog { // the is keyword is like instanceof in java -  checks if the instance type is of the specified type
  221.         print("\((noiseMaker as! Dog).name)") // force cast noiseMaker to Dog (as! - force cast)
  222.     }
  223.     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)
  224.     noiseMaker.makeNoise()
  225. }
  226.  
  227. // example of as without ! or ?
  228. let theDog = Dog(name: "the dog")
  229. theDog as Animal
  230.  
  231.  
  232. // struct vs class
  233.  
  234. class MyClass{
  235.     var name:String
  236.     init(name:String) {
  237.         self.name = name
  238.     }
  239.    
  240.     func printSomething(){
  241.         print("printed from MyClass")
  242.     }
  243. }
  244.  
  245. struct MyStruct{
  246.     var name:String
  247.    
  248.     // note that we dont' have the initializer
  249.    
  250.     func printSomething(){
  251.         print("printed from MyStruct")
  252.     }
  253. }
  254.  
  255. let myClass = MyClass(name: "myClass")
  256. let myStruct = MyStruct(name: "myStuct")
  257.  
  258. myClass.printSomething()
  259. myStruct.printSomething()
  260.  
  261.  
  262.  
  263. struct A{}
  264.  
  265. class X{}
  266. protocol P{}
  267.  
  268.  
  269. //struct B:X{} // a struct cannot inherit from a class
  270. //struct B:A{} // a struct cannot inherit from another struct
  271. //class Y:A{} // a class cannot inherit from a struct
  272. struct B:P{} // a struct can implement a protocol
  273. class Y:P{} // a class and struct can both implement the same protocol
  274.  
  275.  
  276. class Baby: NoiseMaker{
  277.     func makeNoise() {
  278.         print("waaaaaaa")
  279.     }
  280. }
  281.  
  282. struct MotorBike: NoiseMaker{
  283.     func makeNoise() {
  284.         print("VROOOM")
  285.     }
  286. }
  287.  
  288. let moreNoisers:[NoiseMaker] = [Baby(), MotorBike()]
  289.  
  290. for noiseMaker in moreNoisers{
  291.     noiseMaker.makeNoise()
  292. }
  293.  
  294.  
  295. // computed properies
  296. class Rect{
  297.     var side1:Int
  298.     var side2:Int
  299.    
  300.     init(side1:Int, side2:Int) {
  301.         self.side1 = side1
  302.         self.side2 = side2
  303.     }
  304.    
  305.     func getArea()->Int{
  306.         return side1*side2
  307.     }
  308.    
  309.     var area:Int{
  310.         return side1*side2 // if none of get, set, didSet, willSet are written then get is used
  311.     }
  312.    
  313.     private var _color = "white"
  314.     var color:String{
  315.         get{
  316.             return _color
  317.         }
  318.         set{
  319.             self._color = newValue // newValue is the value at the other side of the assignment operator. for instance: myRect.color = "blue" . "blue" is newVlaue
  320.         }
  321.     }
  322.    
  323.    
  324. }
  325.  
  326. let myRect = Rect(side1: 3, side2: 5)
  327. print("the rectangle's area is \(myRect.area)")
  328. print("myRect's color is: \(myRect.color)")
  329. myRect.color = "red"
  330. print("myRect's color is now: \(myRect.color)")
  331.  
  332.  
  333. class Circle{
  334.     var color:String {
  335.         willSet{
  336.             self.radius = 0
  337.         }
  338.     }
  339.     var radius:Int {
  340.         didSet{
  341.            self.circumference = 2.0 * Double.pi * Double(self.radius) // calculate the circumference according to the new value of radius
  342.         }
  343.     }
  344.     private(set) var circumference:Double// the value of circumference depends entirely on the value of radius
  345.    
  346.     init(radius:Int){
  347.         self.color = "blue"
  348.         self.radius = radius
  349.         self.circumference = 2.0 * Double.pi * Double(self.radius)
  350.        
  351.     }
  352.    
  353. }
  354.  
  355. let circle = Circle(radius: 5)
  356. circle.radius = 5
  357. print("the circle's circumference is: \(circle.circumference)")
  358. circle.color = "yellow"
  359. print("the circle's radius after changing the color is: \(circle.radius)")
  360.  
  361.  
  362. // enum
  363.  
  364. enum Direction{
  365.     case north, south, east, west
  366.     /* // another way fo writing this:
  367.      case north
  368.      case south
  369.      case east
  370.      case west
  371.      */
  372. }
  373.  
  374. let dir:Direction = .north
  375.  
  376. switch(dir){
  377.     case .north:
  378.         print("in the north")
  379.     case .south:
  380.         print("in the south")
  381.     case .east:
  382.         print("in the east")
  383.     case .west:
  384.         print("in the west")
  385. }
  386.  
  387. enum Element:CustomStringConvertible{ // an enum can implement a protocol
  388.     case earth, water, fire, air
  389.    
  390.     var description: String { // enum can have members (for instance computed properties like description)
  391.         switch self{ // switch on self to determine which enum case we are
  392.             case .earth:
  393.                 return "earth"
  394.             case .fire:
  395.                 return "fire"
  396.             case .water:
  397.                 return "water"
  398.             case .air:
  399.                 return "air"
  400.         }
  401.     }
  402.    
  403.     func getSideEffect()->String{
  404.         switch self{
  405.         case .earth:
  406.             return "got dirty"
  407.         case .fire:
  408.             return "singed hair"
  409.         case .water:
  410.             return "all wet"
  411.         case .air:
  412.             return "hat got blown away"
  413.         }
  414.     }
  415.    
  416. }
  417.  
  418. let elem:Element = .fire
  419. print("the element is: \(elem)")
  420. print("the element' side effect is: \(elem.getSideEffect())")
  421.  
  422.  
  423. enum Stock:CustomStringConvertible{
  424.     case buy(Int,String), sell(Int), stay
  425.    
  426.     var description: String{
  427.         switch self{ // switch on self to determine which enum case we are
  428.         case .buy(let amount, let company):
  429.             return "bought \(amount) of \(company) stock"
  430.         case .sell(let amount):
  431.             return "sold \(amount)"
  432.         case .stay:
  433.             return "didn't change a thing"
  434.         }
  435.     }
  436.  
  437. }
  438.  
  439. let myStock:Stock = .buy(4,"AAPL")
  440. print("my stock transaction is: \(myStock)")
  441.  
  442. switch myStock{
  443.     case .buy(_, let company) where company=="AAPL": // add an additional condition to the case
  444.         print("bought some AAPL")
  445.     default:
  446.         print("some stock transaction")
  447. }
  448.  
  449.  
  450.  
  451. // extensions
  452.  
  453. extension String{
  454.     // we CANNOT add stored properties in an extension
  455.    
  456.     var isInt:Bool{
  457.         return Int(self) != nil
  458.     }
  459.    
  460.     var toInt:Int{
  461.         return Int(self) ?? 0 // ?? gives a defualt value if the left hand side is n nil
  462.     }
  463. }
  464.  
  465. let st = "23"
  466. print("hello".isInt)
  467. print(st.toInt)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement