Learning from the Geek Academy
1, the definition method needs to be defined in the type (enumeration, struct, Class), cannot be defined independently, the function is defined independently
2. The method either belongs to the type itself or is an instance of the type
3. Cannot execute method independently, execution method must use type or instance as caller
Note: Enumerations, struct methods use static adornments, classes are decorated in class, and are type methods, otherwise they belong to the instance method
1 Import Foundation2 3 classsomeclass{4 func Test () {5println"====test Method ======")6 }7 classfunc Bar (#msg: String) {8println"====bar Method ======, the passed parameter is: \ (msg)")9 }Ten } One //Create an instance Avar sc =SomeClass () - //The sc test method is separated into a function, the preceding type (), () is used to denote the function type, the following method cannot be taken () -var F1: ()--() = Sc.test//if the parentheses are the method that invokes the instance the //separating the bar method of SC into a function -var F2: (String)->void =Someclass.bar - - //then using F1 () is equivalent to calling Sc.test () + F1 () - //then using F2 () is the equivalent of calling Someclass.bar (msg:). +F2 ("Hello") A at - //the external parameter name of the ************ method *************// - classperson{ - var name:string - Init (name:string) { -Self.name =name in } - func Eat (food:string, _ drink:string, cigarette:string) { toprintln"\ (self.name) eating \ (food) drinking \ (drink) smoking \ (cigarette)") + } - } thevar p = person (name:"Tom") *P.eat ("Roast Duck","Beer", Cigarette:"Cigar") $ /*Swift defaults to adding external parameter names outside the first parameter, as well as local parameter names, if not required, with an underscore, adding an external parameter name, not adding a # number*/Panax Notoginseng - /*variable method for *********** value type *************/ the structJkrect { + var x:int A var y:int the var width:int + var height:int - mutating func Movebyx (x:int,y:int) { $self.x + =x $Self.y + =y - } - } thevar rect = jkrect (x: -Y: A, Width: $, Height: -) -Rect.movebyx ( -Y: -)Wuyiprintln"The x-coordinate of the upper- left corner of the rectangle is: \ (rect.x), Y coordinate \ (rect.y)") the /*Note: constant type of struct, enum immutable*/
The operating result is:
Methods in Swift Object-oriented foundation (medium)--swift