Learning #SWIFT Day2

  1. Enumeration & Structures
    1. enum Rank: Int {

      case Ace = 1

      case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten

      case Jack, Queen, King

      func simpleDescription() -> String {

      switch self {

      case .Ace:

      return “ace”

      case .Jack:

      return “jack”

      case .Queen:

      return “queen”

      case .King:

      return “king”

      default:

      return String(self.toRaw())

      }

      }

      }
      let ace = Rank.Ace
      let aceRawValue = ace.toRaw()    //get raw value

      }

      let aceEnumValue = ace.fromRaw()

    2. struct Card {  // struct support methods and init. Diff with class pass by copy, class pass by reference

      var rank: Rank

      var suit: Suit

      func simpleDescription() -> String {

      return “The \(rank.simpleDescription()) of \(suit.simpleDescription())”

      }

       

  2. Protocol & Extension
    1. protocol ExampleProtocol {

      var simpleDescription: String { get }

      mutating func adjust()

      }

      class SimpleClass: ExampleProtocol {
      var simpleDescription: String = “A very simple class.”
      var anotherProperty: Int = 69105
      func adjust() {
      simpleDescription += ” Now 100% adjusted.”
      }
      }
      var a = SimpleClass()
      a.adjust()
      let aDescription = a.simpleDescription

      struct SimpleStructure: ExampleProtocol {
      var simpleDescription: String = “A simple structure”
      mutating func adjust() {
      simpleDescription += ” (adjusted)”
      }
      }

    2. use extension to add functionality to an existing type (new method / computed properties)extension Int: ExampleProtocol {
      var simpleDescription: String {
      return “The number \(self)”
      }
      mutating func adjust() {
      self += 42
      }
      }
      7.simpleDescription

       

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s