Swift Tutorial - Tutorialspoint

(backadmin) #1
pri.result()
sum.result()

When we run the above program using playground, we get the following result:


Inside Self Block: 900
Inside Self Block: 1500
Result is: 880
Result is: 850
Result is: 1480
Result is: 1450

Modifying Value Types from Instance Methods


In Swift language structures and enumerations belong to value types which cannot be
altered by its instance methods. However, swift language provides flexibility to modify the
value types by 'mutating' behavior. Mutate will make any changes in the instance methods
and will return back to the original form after the execution of the method. Also, by the
'self' property new instance is created for its implicit function and will replace the existing
method after its execution


struct area {
var length = 1
var breadth = 1

func area() - > Int {
return length * breadth
}

mutating func scaleBy(res: Int) {
length *= res
breadth *= res

println(length)
println(breadth)
}
}

var val = area(length: 3 , breadth: 5 )
Free download pdf