首页投稿(暂停使用,暂停投稿)程序员iOS Developer

Swift入门----06字符串&字典&数组

2016-04-23  本文已影响274人  断剑

字符串

var str1: String = "Hello"


###字符串拼接
```swift
var str1 = "hello"
var str2 = "word"
let num = 2016
str1 += str2
print(str1)
print("\(str1) \(str2) \(num)")
//print结果分别为:helloword\n 与 "helloword word 2016\n"

格式化字符串

方式一:
let age = 20
let name = "zhangsan"
//目标:name = zhangsan , age = 20
//方法见上字符串拼接
var str = "name = \(name) , age = \(age)"
方式二:
//目标:09:09:09
var str = String(format: "%02d: %02d: %02d", arguments: [9,9,9])

遍历字符串

var str = "hello word"
for l in str.characters
{
   if l == "l"
   {
       print(123)   //打印2次
   }
   print(l) //打印10次
}

字符串截取

//OC 写法 
var str : NSString = "hello word"
var str1 = "hello word" as NSString
var subStr = str.substringWithRange(NSMakeRange(0, 5))
//subStr 为 hello

//Swift的写法
let str: String = "hello word"
var subStr = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex))
print(subStr)

出字符串截取之外,在 Swift 中字符串推荐使用 String 类型

数组

let arr = ["tianxia","wushuang"]
print(arr)  //输出结果:["tianxia","wushuang"]
//遍历数组每一个元素
for a in arr
{
  print("-----") //输出结果:两行-----
}
//像 OC 一样打印
print(arr as NSArray) 
/* 打印结果
(
    tianxia,
    wushuang
)
*/

数组中保存的对象类型

// 数组中保存的都是字符串
let arr = ["tianxia", "wushuang"]

// 数组中保存的是 NSObject
let arr1 = ["tianxia", 1]

数组常见操作

//定义只能保存字符串类型的数组
var array: [String]

// 初始化数组
array = ["tianxia"]

//添加元素
array.append("wushuang")
print(array)
//输出结果:["tianxia", "wushuang"]

//删除元素
array.removeAtIndex(0)
print(array)
//输出结果:["wushuang"]


//删除所有元素
//array.removeAll()
array.removeAll(keepCapacity: true)
print(array.capacity)

//注意数组容量的变化
for i in 0..<10 {
    array.append("\(i)")
    print("\(array) --- \(array.capacity)")
}
/* 输出结果
["0"] --- 1
["0", "1"] --- 2
["0", "1", "2"] --- 4
["0", "1", "2", "3"] --- 4
["0", "1", "2", "3", "4"] --- 8
["0", "1", "2", "3", "4", "5"] --- 8
["0", "1", "2", "3", "4", "5", "6"] --- 8
["0", "1", "2", "3", "4", "5", "6", "7"] --- 8
["0", "1", "2", "3", "4", "5", "6", "7", "8"] --- 16
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] --- 16
*/

//实例化新的数组
var array1 = [String]()
array1.append("fengyun")
array1.append("baibian")

//拼接数组
array += array1
print(array)
//输出结果:["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "fengyun", "baibian"]

注意

数组容量变化部分,本人不是太理解容量的变化,哪位朋友知道的,还请告知,谢谢大家了

字典

//定义并实例化字典
var dict = [String: AnyObject]()
//var dict1 = [String : NSObject]()
//var dict2 = ["key":30 , "key1":"40"]
dict["name"] = "zhangsan"
dict["age"] = 30
print(dict)
//输出结果:["age": 30, "name": zhangsan]

//获取value
dict["name"]

//遍历字典
//OC
for keys in dict.keys
{
    print(keys)
}

//利用元祖类型遍历字典
for (k ,v) in dict
{
    print(k)
    print(v)
}

//新增key、value
dict["sex"] = "boy"

//更新key、value
dict["age"] = 20

//删除
dict.removeValueForKey("age")

//合并字典
var dict1 = ["time":2016,"date":"4-22"]
for (key, value) in dict1
{
  dict[key] = value
}
print(dict)
//输出结果:["name": zhangsan, "date": 4-22, "time": 2016, "sex": boy]
上一篇 下一篇

猜你喜欢

热点阅读