Swift擴充(Extension)

來源:互聯網
上載者:User

標籤:toc   line   struct   existing   font   exist   構造   pac   erp   

在現有類和結構體的類型基礎上,擴充新的功能。

文法:

extension SomeType{// new functionality to add to SomeType goes here}An extension can extend an existing type to make itadopt one or more protocols.Where this is the case,the protocol names are written in exactly the sameway as for a class or structure:extension          SomeType:            SomeProtocol,AnotherProtocol {// implementation of protocol requirements goes here}

計算屬性

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 is \(oneInch) meters")// prints "One inch is 0.0254 meters"let threeFeet =3.ftprintln("Three feet is \(threeFeet) meters")// prints "Three feet is0.914399970739201 meters"let aMarathon = 42.km + 195.mprintln("Amarathon is \(aMarathon) meters long")

使用構造器

struct Size {varwidth = 0.0, height = 0.0}struct Point {var x = 0.0, y = 0.0} struct Rect {var origin = Point()var size= Size()}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)//調用 Rect 結構體構造器} }let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))

方法擴充

struct Size { varwidth = 0.0, height = 0.0}struct Point {var x = 0.0, y = 0.0}struct Rect {var origin = Point()var size= Size()}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)//調用 Rect 結構體構造器}}let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))


Swift交流討論論壇論壇:http://www.cocoagame.net

歡迎增加Swift技術交流群:362298485


Swift擴充(Extension)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.