Swift语言的类扩展是一个强大的工具,我们可以通过类扩展完成如下事情:
示例2:给Double增加mm,cm等方法,进行进制转换
31
3,提供新的构造器
4,定义下标脚本
5,是一个已有的类型符合某个协议
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
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_136_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
@H_949_403@}
mm()->
return
"\(self/1)mm"
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())
|