|
28 | 28 | <article> |
29 | 29 | <h2>Swift mode</h2> |
30 | 30 | <form><textarea id="code" name="code"> |
31 | | -// |
32 | | -// TipCalculatorModel.swift |
33 | | -// TipCalculator |
34 | | -// |
35 | | -// Created by Main Account on 12/18/14. |
36 | | -// Copyright (c) 2014 Razeware LLC. All rights reserved. |
37 | | -// |
38 | | - |
39 | | -import Foundation |
40 | | - |
41 | | -class TipCalculatorModel { |
42 | | - |
43 | | - var total: Double |
44 | | - var taxPct: Double |
45 | | - var subtotal: Double { |
46 | | - get { |
47 | | - return total / (taxPct + 1) |
48 | | - } |
49 | | - } |
50 | | - |
51 | | - init(total: Double, taxPct: Double) { |
52 | | - self.total = total |
53 | | - self.taxPct = taxPct |
54 | | - } |
55 | | - |
56 | | - func calcTipWithTipPct(tipPct: Double) -> Double { |
57 | | - return subtotal * tipPct |
58 | | - } |
59 | | - |
60 | | - func returnPossibleTips() -> [Int: Double] { |
61 | | - |
62 | | - let possibleTipsInferred = [0.15, 0.18, 0.20] |
63 | | - let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20] |
| 31 | +protocol HeaderViewProtocol { |
| 32 | + func setTitle(_ string: String) |
| 33 | +} |
64 | 34 |
|
65 | | - var retval = [Int: Double]() |
66 | | - for possibleTip in possibleTipsInferred { |
67 | | - let intPct = Int(possibleTip*100) |
68 | | - retval[intPct] = calcTipWithTipPct(possibleTip) |
| 35 | +struct AnyHeaderView { |
| 36 | + let view: UIView |
| 37 | + let headerView: HeaderViewProtocol |
| 38 | + init<T: UIView>(view: T) where T: HeaderViewProtocol { |
| 39 | + self.view = view |
| 40 | + self.headerView = view |
69 | 41 | } |
70 | | - return retval |
| 42 | +} |
71 | 43 |
|
72 | | - } |
| 44 | +let header = AnyHeaderView(view: myView) |
| 45 | +header.headerView.setTitle("hi") |
73 | 46 |
|
74 | | - func funWithStrings() { |
75 | | - var numLines = 3 |
76 | | - print("This is a string!") |
77 | | - print(""" |
78 | | - This is a |
79 | | - multi-line |
80 | | - string! |
81 | | - """) |
82 | | - print("The preceding string had \(numLines) lines!") |
83 | | - } |
| 47 | +struct HeaderView { |
| 48 | + let view: UIView |
| 49 | + let setTitle: (String) -> () |
| 50 | +} |
84 | 51 |
|
| 52 | +var label = UILabel() |
| 53 | +let header = HeaderView(view: label) { str in |
| 54 | + label.text = str |
85 | 55 | } |
| 56 | +header.setTitle("hello") |
86 | 57 | </textarea></form> |
87 | 58 |
|
88 | 59 | <script> |
|
0 commit comments