Posted By

chrisaiv on 03/01/15


Tagged

playground swift


Versions (?)

SWIFT: Value & Reference Types


 / Published in: Objective C
 

Notes about reference types

  1. // Variables and CONSTANTS can reference two types of values: Values and Reference types
  2.  
  3. import Cocoa
  4.  
  5. var str = "Hello, playground"
  6.  
  7. /** ** ** ** ** ** ** ** ** **
  8. Value Types
  9. 1: They only have a single reference to them.
  10. 2: Types of Objects: Structures, Enumerations, Tuples,
  11. 2: Assignment to value types results in a copy to the value.
  12. ** ** ** ** ** ** ** ** ** **/
  13.  
  14.  
  15. /** ** ** ** ** ** ** ** ** **
  16. Reference Types
  17. 1: They use a memory management model like objective C
  18. 2: Types of Objects: Classe and Functions
  19. 3: There are no copies of references types, only associations.
  20. 4: Assigning a var or let to a Class or Function only increases the reference count to the value. Assigment DOES NOT MAKE A NEW COPY OF THE VALUE
  21. 5: Single inheritance model
  22. 6: Supports Polymorphism
  23. 7: Supports Classes and Instances
  24. 8: Classes & instances can have their own methods
  25. 9: Classes & instances can have their own properties
  26. ** ** ** ** ** ** ** ** ** **/
  27.  
  28. class Person {
  29. var firstName:String
  30. var lastName:String
  31.  
  32. init(firstName:String, lastName:String){
  33. self.firstName = firstName
  34. self.lastName = lastName
  35. }
  36.  
  37. func saySomething(message:String){
  38. println("\(firstName) \(lastName) says '\(message)'")
  39. }
  40.  
  41. class func saySomething(message:String) {
  42. println("...and the people all say \(message)")
  43. }
  44. }
  45.  
  46. //New Instance
  47. let person = Person(firstName: "Chris", lastName: "Aiv")
  48. person.saySomething("HEllo World")
  49.  
  50. //Call class function
  51. Person.saySomething("OH YAY")
  52.  
  53.  
  54. func printPerson(p:Person){
  55. println("Person is \(p.firstName) \(p.lastName)")
  56. }
  57.  
  58. let stooges = ["Larry", "Moe", "Curly"]
  59. stooges.filter({
  60. (name:String) -> Bool in return name.hasPrefix("L")
  61. })
  62.  
  63.  
  64. /** ** ** ** ** ** ** ** ** **
  65. Various ways to call a function
  66. ** ** ** ** ** ** ** ** ** **/
  67.  
  68. //func printperson(person:Person)
  69.  
  70. //func printPerson(person
  71.  
  72. /** ** ** ** ** ** ** ** ** **
  73. Various ways to call a closure
  74. ** ** ** ** ** ** ** ** ** **/
  75.  
  76. //Explicit
  77. stooges.filter({(name: String) -> Bool in
  78. return name.hasPrefix("L")
  79. })
  80.  
  81. //Shorthand
  82. stooges.filter({$0.hasPrefix("L")})
  83.  
  84. //Last argument in the class
  85. stooges.filter() { name -> Bool in
  86. name.hasPrefix("L")
  87. }

Report this snippet  

You need to login to post a comment.