daily pastebin goal
24%
SHARE
TWEET

Untitled

a guest Jan 17th, 2019 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class People{
  2.    
  3.     let firstName : String
  4.     let lastName : String
  5.    
  6.     var fullName : String{
  7.         get{
  8.             return firstName + " " + lastName;
  9.         }
  10.     }
  11.     var age : Int
  12.    
  13.     init(firstName : String, lastName : String, age : Int){
  14.         self.firstName = firstName
  15.         self.lastName = lastName
  16.         self.age = age
  17.        
  18.     }
  19. }
  20.  
  21. let p1 = People(firstName: "first P1", lastName: "last P1", age: 10)
  22. let p2 = People(firstName: "first P2", lastName: "last P2", age: 20)
  23.  
  24. let peoples = [p1,p2]
  25.  
  26. /// vairable with for loop
  27. extension Array where Element : People{
  28.    
  29.     var averageAge : Int {
  30.        
  31.         var totalAge = 0;
  32.        
  33.         for people in self{
  34.             totalAge += people.age
  35.         }
  36.        
  37.         return totalAge / self.count;
  38.        
  39.     }
  40. }
  41.  
  42. print( peoples.averageAge)
  43.  
  44. // vairable with reduce
  45. extension Array where Element : People{
  46.    
  47.     var averageAgeWithReduce : Int {
  48.        
  49.         let totalAge = self.reduce(0){ (result, next )->Int in
  50.            
  51.             return result + next.age
  52.            
  53.         }
  54.        
  55.          return totalAge / self.count
  56.        
  57.        
  58.     }
  59. }
  60.  
  61. print( peoples.averageAgeWithReduce)
  62.  
  63.  
  64.  
  65. // method with reduce
  66. extension Array where Element : People{
  67.    
  68.     func averageAgeWithMethod() -> Int {
  69.        
  70.         let totalAge = self.reduce(0){ (result, next )->Int in
  71.            
  72.             return result + next.age
  73.            
  74.         }
  75.        
  76.         return totalAge / self.count
  77.        
  78.     }
  79. }
  80.  
  81. print( peoples.averageAgeWithMethod())
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top