这篇文章主要介绍“如何扩展现有类、结构体、枚举”,在日常操作中,相信很多人在如何扩展现有类、结构体、枚举问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何扩展现有类、结构体、枚举”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
//扩展 Double 计算属性 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 print("One inch is \(oneInch) meters") //One inch is 0.0254 meters let threeFeet = 3.ft print("Three feet is \(threeFeet) meters") //Three feet is 0.914399970739201 meters
//扩展初始化器 struct Rect{ var x = 0.0, y = 0.0 var width = 0.0, height = 0.0 } extension Rect { init(pos: [Double], size: [Double]) { self.init(x: pos[0], y: pos[1], width: size[0], height: size[1]) } } let r = Rect(pos: [0.0, 0.0], size: [4.0, 4.0])
//扩展方法 extension Int { func repeatTalk(talk: () -> Void) { for _ in 0..<self { talk() } } } 5.repeatTalk { print("Hi") } /* Hi Hi Hi Hi Hi */
//修改实例本身 mutating extension Int { mutating func square() { self = self * self } } var a = 5 a.square() print(a) //25
//扩展下标 extension Int { subscript(index: Int) -> Int { var base = 1 for _ in 0..<index { base *= 10 } return (self/base) % 10 } } print(12345678[0]) print(12345678[1]) print(12345678[2]) print(12345678[3]) print(12345678[4]) /* 8 7 6 5 4 */
//扩展内嵌类型 extension Int { enum Kind { case negative, zero, positive } var kind: Kind { switch self { case 0: return .zero case let x where x > 0: return .positive default: return .negative } } } print(4.kind) //positive
到此,关于“如何扩展现有类、结构体、枚举”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。