Swift扩展示例
我最初想知道如何做这样的事情
UIColor.myCustomGreen 所以我可以定义我自己的颜色,并在我的应用程序中使用它们。 我之前已经研究了扩展名,我以为我可以用它来解决我的问题,但是我不记得如何设置扩展。在撰写本文时,Google搜索“Swift扩展”导致documentation,several长时间tutorials,并且相当无用的Stack Overflow question。 所以答案是在那里,但它需要一些挖掘通过文档和教程。我决定写这个问题和下面的答案,为Stack Overflow增加一些更好的搜索关键字,并提供一个快速回顾如何设置扩展。 具体我想知道: >扩展位置在哪里(文件和命名约定)?
创建扩展名
添加一个新的swift文件,文件>新>文件…> iOS>来源> Swift文件,但你可以称呼他们想要什么。 一般的命名约定是将它称为TypeName NewFunctionality.swift。 示例1 – 双重转换 import Swift // or Foundation extension Double { func celsiusToFahrenheit() -> Double { return self * 9 / 5 + 32 } func fahrenheitToCelsius() -> Double { return (self - 32) * 5 / 9 } } 用法: let boilingPointCelsius = 100.0 let boilingPointFarenheit = boilingPointCelsius.celsiusToFahrenheit() print(boilingPointFarenheit) // 212.0 示例2 – 字符串Shortcuts.swift import Swift // or Foundation extension String { func replace(target: String,withString: String) -> String { return self.replacingOccurrences(of: target,with: withString) } } 用法: let newString = "the old bike".replace(target: "old",withString: "new") print(newString) // "the new bike" Here是一些更常见的字符串扩展。 示例3 – UIColor CustomColor.swift import UIKit extension UIColor { class var customGreen: UIColor { let darkGreen = 0x008110 return UIColor.rgb(fromHex: darkGreen) } class func rgb(fromHex: Int) -> UIColor { let red = CGFloat((fromHex & 0xFF0000) >> 16) / 0xFF let green = CGFloat((fromHex & 0x00FF00) >> 8) / 0xFF let blue = CGFloat(fromHex & 0x0000FF) / 0xFF let alpha = CGFloat(1.0) return UIColor(red: red,green: green,blue: blue,alpha: alpha) } } 另见here。 用法: view.backgroundColor = UIColor.customGreen 笔记 >一旦定义了扩展名,就可以像应用程序中的内置函数一样在应用程序的任何位置使用它。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |