示例1:给字符串String类添加下标脚本,支持索引访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 @H_502_112@ 42 43 44 45 46 47 48 49 50 51 | extension String { subscript(start: Int ,length: ) -> String { get { return ( self as Nsstring ).substringWithRange( NSRange (location: start,length: length)) } set { let tmp = self var s = "" e = "" for (IDx,item) in tmp.characters. enumerate () { if (IDx < start) { s += "\(item)" } else { e += "\(item)" } } self = s + newValue + e } } subscript(index: String { { return String [ .startIndex.advancedBy(index)]) } { self @H_704_301@= "" () { IDx == index { += "\(newValue)" } else { "\(item)" } } } } } str = "hangge.com" print (str[7,3]) (str[7]) str[7,3] = "COM" str[0] = "H" (str[0,10]) |
示例2:给Double增加mm,cm等方法,进行进制转换
Double func mm()-> return "\(self/1)mm" @H_25_403@} cm()-> String "\(self/10)cm" } dm()-> { "\(self/100)dm" } m()-> String { "\(self/1000)m" } km()-> String { "\(self/(1000*1000))km" value = 2000000000.0 (value.mm()) (value.cm()) (value.dm()) (value.m()) (value.km()) |
以上是内存溢出为你收集整理的Swift - 类扩展(extension)全部内容,希望文章能够帮你解决Swift - 类扩展(extension)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)