0

I want to write a class with 2 computed properties, where the second one references the first. I tried this:

class GraphView: UIView {
    var graphVisibleSize: CGSize {
        return CGSize(
            width:  self.bounds.size.width  / 40,
            height: self.bounds.size.height / 40)
    }
    var graphRect = CGRect {
        return CGRect(
            center: CGPointZero,
            size: self.graphVisibleSize)
    }
}

However, that results in an error. Xcode gives an error on the size: self.graphVisibleSize line and says:

'GraphView -> () -> GraphView' does not have a member named 'graphVisibleSize'

What does this mean? Specifically:

  1. What does the GraphView -> () -> GraphView part mean?

  2. Why can it not see the graphVisibleSize member that is right above it?

  3. Bonus question: I tried to replicate this in a test class and ended up writing a class that works just fine - but I don't understand what's different! Here's the one I wrote just as a test:

    func mungeString(str: String) -> String {
        var newString = "--asdf--\(str)--qwer--"
        return newString
    }
    
    class TestClass: UIView {
        var baseA: String = "This is a string"
        var baseB: String {
            return "This is a computed string"
        }
        var changedA: String {
            return self.baseA.lowercaseString
        }
        var changedB: String {
            return mungeString(self.baseB)
        }
    }
    

    Why does this code work just fine, but the original code give me an error?

Micah R Ledbetter
  • 1,040
  • 1
  • 12
  • 28
  • `self` is not the GraphView. notice how `baseA` is refered to directly in the second example. – njzk2 Aug 21 '15 at 03:19
  • Ahh, sorry, I was trying things out before posting and didn't fix that. I've changed my test class now to look for `self.baseA` and `self.baseB`. – Micah R Ledbetter Aug 21 '15 at 03:28
  • Also, when I *remove* `self.` from the line in the `GraphView` class, so that it becomes `size: graphVisibleSize`, I get a different error: `'GraphView.Type' does not have a member named 'graphVisibleSize'`. It still can't find the member, and I'm still confused as to why – Micah R Ledbetter Aug 21 '15 at 03:30
  • The direct initializer of an instance property cannot depend on another instance property because during initialization there is no instance yet. See the duplicate link. There are a _lot_ of other answers to this; please search before posting. – matt Aug 21 '15 at 03:32
  • I don't think the dupe is my issue. I was able to fix it with David Skrundz' solution below. – Micah R Ledbetter Aug 21 '15 at 03:39

1 Answers1

1

The issue is caused by this line

var graphRect = CGRect {

it should instead be

var graphRect: CGRect {

like the other vars

David Skrundz
  • 13,067
  • 6
  • 42
  • 66