Method
A method is a function that is associated with some particular type. classes, structs, enumerations can define instance methods , and instance methods encapsulate specific tasks and functions for instances of a given type. classes, structs, enumerations can also define type methods , and type methods are associated with the type itself. Type methods are similar to class methods in Objective-c.
instance Method
Class Counter { var count = 0 //Implement two simple methods func increment () { count + = 1 } func IncrementBy (AMO Unt:int) { count + = Amount }}let counter = Counter () counter.increment () print (counter.count)// Print out: 1counter.incrementby (5) print (Counter.count)//Print out: 5
Self Property
You do not usually need to use the Self property, but in some methods the parameter name is the same as a property name, you need to use the Self property, the main function is to distinguish the property name
struct Point { var x = 0.0, y = 0.0 func ISTOTHERIGHTOFX (x:double), Bool { ////////when the argument (x) is passed in to match the declared property Use the Self property to differentiate return self.x > x }}let point = Point (x:5.0, y:3.0) if POINT.ISTOTHERIGHTOFX (1.0) { print ("T He point was to the right of the line where x = = 1.0 ")}
instance methods modify value types
Structs and enumerations are value types, so modifying the properties of a value type using an instance method requires special handling, otherwise it cannot be modified
struct Point { var x = 0.0, y = 0.0 //If you want to modify the value type property, you need to add the "mutating" keyword mutating func movebyx (deltax:double, Del tay:double) { self.x + = deltax Self.y + = DeltaY //self = Point (x:x + deltax, y:y + deltay) so write Effect }}var point = Point (x:5.0, y:3.0) Point.movebyx (8.0, deltay:2.0) print (point)
Enum Stateswitch {case- Off, Low, high mutating func next () {switch-Self {case . Off: Self =. Low Case . Low: Self =. High Case . High: Self =. Off } }}var ovenlight = StateSwitch.OffovenLight.next ()//is now Low state ovenlight.next ()//is now high state
Type Method
An instance method is a method that is called by an instance of the type. You can also define a method called by the type itself, which is called a type method . declares struct and enum type methods, plus keywords before the method's keywords func
static
. Class may use keywords class
to allow subclasses to override the implementation of the parent class.
Class SomeClass { class func SomeFunc (), SomeClass { return SomeClass () }}//type method can be called directly using type without creating an instance let SomeClass = Someclass.somefunc () struct SomeStruct { static func SomeFunc () { }}somestruct.somefunc ()
Learning swift--Methods