定义下标脚本之后,可以使用“[]”来存取数据类型的值。
示例1改进:
通过类扩展,也可以直接给String类添加索引功能,代码如下:
51
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
52
53
54
55
56
57
58
59
60
|
class
SubString
{
var
str:
String
=
""
init
(str:
)
{
self
.str = str;
}
/**下标脚本:获取/设置部分字符串**/
subscript(start:
Int
,length:
) ->
String
{
get
{
}
set
{
let
tmp = str
str =
""
s =
""
e =
""
if
(idx < start)
{
s +=
"\(item)"
} else if
(idx >= start + length)
{
e +=
"\(item)"
}
}
str = s + newValue + e
}
}
/**下标脚本:获取/设置字符**/
subscript(index:
String
{
{
return
(str[str.startIndex.advancedBy(index)])
}
{
tmp = str
""
() {
idx == index {
str +=
"\(newValue)"
}
else
{
"\(item)"
}
}
}
}
}
str =
SubString
(str:
"hangge.com"
)
(str[7])
//获取字符:c
str[7,3] =
"COM"
//设置部分字符串
str[0] =
"H"
//设置部分字符
(str[0,10])
//Hangge.COM
|
extension
String
String
{
(
self
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,length: length))
{
tmp =
self
""
""
() {
(idx < start)
{
"\(item)"
} else
{
"\(item)"
}
}
= s + newValue + e
}
}
String
{
[
.startIndex.advancedBy(index)])
{
self
""
() {
idx == index {
+=
"\(newValue)"
"\(item)"
}
}
}
}
"hangge.com"
(str[7])
"COM"
"H"
示例2:使用一维数组结合下标方法一定程度上模拟实现了二维数组
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。 相关推荐 |