Lesson 12 of 15
Structs
Structs
Structs are value types that group related data and behavior:
struct Point {
var x: Int
var y: Int
func distanceFromOrigin() -> Double {
return Double(x * x + y * y)
}
}
let p = Point(x: 3, y: 4)
print(p.x) // 3
Memberwise Initializer
Swift automatically generates an initializer from the properties:
let p = Point(x: 3, y: 4) // free memberwise init
Mutating Methods
Structs are value types, so methods that modify properties must be marked mutating:
struct Counter {
var count = 0
mutating func increment() { count += 1 }
}
Your Task
Create a Rectangle struct with width and height (both Int), and two methods:
area() -> Int— returnswidth * heightperimeter() -> Int— returns2 * (width + height)
JS Transpiler loading...
Loading...
Click "Run" to execute your code.