FusionPointInc FusionPointInc - 1 month ago 9
Swift Question

Why won't figure.area = ... not work? Swift 3.0

struct Shape{

struct Rectangle {
var length = 0
var width = 0
var area: Float = 0

}

struct Square {
var length = 0
var width = 0
var area: Float = 0

}

func area(length: Float, width: Float) -> Float {
return length * width
}

}

var figure = Shape.Rectangle()
figure.width = 2; figure.length = 3

figure.area = Shape.area(figure.length,figure.width)


Why won't figure.area = ... not work? It allows me to write that in xCode but it doesn't run properly in the PlayGround. Can you declare a function inside of a struct? If yes, how do I declare this (
figure.area = Shape.area(figure.length,figure.width)
) properly?

Answer

You haven initialised an instance of Shape when you call area, so the compiler will be confused.

You can either initialise a Shape instance and then call area

Shape().area(etc...)

Or make the area function a static function, then you can call it like you have been (a much better option anyways)

E.g.

struct Shape{

....

    static func area(length: Float, width: Float) -> Float {
        return length * width
    }

}

Also, with swift 3, all arguments must be explicitly written unless there is an underscore before them in the function declaration. So you function call should look like this

figure.area = Shape.area(length: figure.length, width: figure.width)
Comments