Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift Classes and Objects Classes and Their Methods

How can I call the incrementBy method?

Regarding the method incrementBy(), I'm having trouble calling the function within class Button {}. I'm wondering if I'm prefixing incrementBy() incorrectly.

class Button {
    var width: Double
    var height: Double

    init(width:Double, height:Double){
        self.width = width
        self.height = height
    }
    func incrementBy(points: Double) -> (Double, Double) {
        width = width + points
        height = height + points
        return (width, height)
    }
}

var width = 10
var length = 15

Button.incrementBy(7)

I'm getting error: type 'Button' does not conform to protocol 'IntegerLiteralConvertible', referencing Button.incrementBy(7).

4 Answers

Wayne Sang
Wayne Sang
3,157 Points

Your class is fine, but you need to create an instance of it in order to use to give it defaults, and to use that method.

The second time you create "width" and "height" variables they're not being used at all, they're outside the scope of that class. You can delete those. What you want after the class definition is:

var newButton = Button(width: 10, height: 15)

newButton.incrementBy(7)

Thanks Wayne. That was on point.

William Li
PLUS
William Li
Courses Plus Student 26,865 Points

Also, David, there's one more thing. Some method doesn't need to have return value, incrementBy is one of those; it perform addition operation on width and height, and that's all it does, you could simply write it as

      func incrementBy(points: Double) {
        width = width + points
        height = height + points
    }
AR Ehsan
AR Ehsan
7,912 Points

func incrementBy(points: Double) { width = width + points height = height + points } Tell me if that helped you!