zoukankan      html  css  js  c++  java
  • Swift扩展(Extension)

    在现有类和结构体的类型基础上,扩展新的功能。

    语法:

    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.mm
    println("One inch is (oneInch) meters")
    // prints "One inch is 0.0254 meters"
    let threeFeet =3.ft
    println("Three feet is (threeFeet) meters")
    // prints "Three feet is0.914399970739201 meters"
    let aMarathon = 42.km + 195.m
    println("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( 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( 3.0, height: 3.0))
    


    Swift交流讨论论坛论坛:http://www.cocoagame.net

    欢迎增加Swift技术交流群:362298485


  • 相关阅读:
    毕业设计:文献参考(十九)
    毕业设计:文献参考(十八)
    毕业设计:文献参考(十七)
    毕业设计:文献参考(十六)
    毕业设计:文献参考(十五)
    毕业设计:文献参考(十四)
    毕业设计:文献参考(十三)
    毕业设计:文献参考(十二)
    毕业设计:文献参考(十一)
    MySQL8.0失踪记-连接时2003报错、服务列表不显示、服务启动后立即停止、重装卡在starting server
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7076464.html
Copyright © 2011-2022 走看看