Extend the new functionality based on the types of existing classes and struct bodies.
Grammar:
Extension sometype{//new functionality to add to SomeType goes Here}an extension can extend a existing type to make Itad Opt one or more protocols. Where This is the Case,the protocol names be written in exactly the Sameway as for a class or structure:extension Som EType: Someprotocol,anotherprotocol {//implementation of protocol requirements goes here}
Calculated properties
Extension Double{var km:double {return self * 1_000.0}var m:double {return self}var cm:double {return self/100.0 } var mm:double {return self/1_000.0}var ft:double {return self/3.28084}}let oneinch = 25.4.mmprintln ("One inch I s \ (oneinch) meters ")//prints" one inch are 0.0254 meters "let Threefeet =3.ftprintln (" Three feet are \ (threefeet) meters ")/ /Prints "three feet is0.914399970739201 meters" let Amarathon = 42.km + 195.mprintln ("Amarathon are \ (Amarathon) meters lon G ")
Using constructors
struct Size {varwidth = 0.0, height = 0.0}struct point {var x = 0.0, y = 0.0} struct Rect {var origin = point () var size= S Ize ()}extension rect{init (Center:point, size:size) {Let Originx = center.x-(SIZE.WIDTH/2) Let Originy = Center.y-( SIZE.HEIGHT/2) Self.init (Origin:point (X:originx, Y:originy), size:size)//Call rect struct constructor}}let centerrect = rect (center : Point (x:4.0, y:4.0), Size:size (width:3.0, height:3.0))
Method extension
struct Size {varwidth = 0.0, height = 0.0}struct point {var x = 0.0, y = 0.0}struct Rect {var origin = point () var size= S Ize ()}extension rect{init (Center:point, size:size) {Let Originx = center.x-(SIZE.WIDTH/2) Let Originy = Center.y-( SIZE.HEIGHT/2) Self.init (Origin:point (X:originx, Y:originy), size:size)//Call Rect struct constructor}}let centerrect = rect (center: Point (x:4.0, y:4.0), Size:size (width:3.0, height:3.0))
Swift Exchange Discussion Forum Forum: http://www.cocoagame.net
Welcome to add Swift Technology Group: 362298485
Swift Extension (Extension)