1

I read a few tutorial about swift, and have made simple counter app, but I want modify it to leave controller clean and logic move to external class:

In ViewController.swift i have

 class ViewController: UIViewController {
      var counter: Counter?

      override func viewDidLoad() {
        super.viewDidLoad()
        counter = Counter(label: labelCounter)
        counter.renderInit()
      }
    }

and I have Counter class:

 class Counter: NSObject {
      var label: UILabel?

      init(label: UILabel) {
        self.label = label
      }

      func renderInit() {
        ...
      }
    }

Unfortunatelly in controller on line counter.renderInit() I see error message:

'Counter?' does not have a member named 'renderInit'

Geet
  • 2,427
  • 2
  • 21
  • 39
wafcio
  • 81
  • 1
  • 4
  • possible duplicate of [NSIndexPath? does not have a member name 'row' error in Swift](http://stackoverflow.com/questions/24040405/nsindexpath-does-not-have-a-member-name-row-error-in-swift) – Jack Jul 24 '14 at 18:26

2 Answers2

1

Change counter.renderInit() to one of these:

counter?.renderInit()
counter!.renderInit()

Counter? is an optional type. You need to unwrap it. Doing ? will ignore the method if counter is nil, and ! will force it to unwrap and throw an error if it does not exist.

Check out this page in Swift's documentation for more on optionals.

Jonathan J.
  • 171
  • 6
  • awesome, thanks. I have read documentation before and I know that ? mean optional type, but I can't find similary example. – wafcio Jul 25 '14 at 19:35
0

ok, I move step forward and have another problem with call method object.

class Counter: NSObject {
  var label: UILabel?

  init(label: UILabel) {
    self.label = label
  }

  func renderInit() {
    label?.text = String(counter)
  }
}

I got "Cannot assign to the result of this expression." (for line where I want assign number converted to string, to label text.

I read documentation and couple of tutorials, but with learning new thing it is good to look on example and to it in similar way. Unfortunatelly Swift is young language and there are not many examples. (I am Ruby language programmer).

wafcio
  • 81
  • 1
  • 4