//定义变量和常量的字符串并输出
var myvarString = "original value"
myvarString = "my value"
print(myvarString)
let myletName = "abc"
print(myletName);
//定义变量和常量的数字并输出
var myvarInt = 0
myvarInt = 2
let myfloat:Float =4.00//double 转换为float
print("myint value:\(myvarInt)\nmyfloat value:\(myfloat)")//换行输出为“\n”对象输出为“\(对象名)”
//字符串和数字的拼接并输出
let label = "The width is"
let width = 90
let widthLabel = label + String(width)
print("width desprition:\(widthLabel)")
//布尔值的定义和判断
var isSuccess = false
isSuccess = true
if isSuccess{
print("Bool value is Yes")
}
//定义空字符串数组
var shoppingList:[String] = []
//判断数组是否为空
if shoppingList.isEmpty{
print("list empty")
}
shoppingList = ["catfish","water","tulips","blue paint"]
shoppingList[1] = "bottle of water"//改变数组指定索引的值
shoppingList.append("endStr")//数组末尾添加元素
shoppingList += ["endingStr"]//数组拼接
shoppingList.insert("insertStr", atIndex:0)//在指定位置添加元素
shoppingList.removeAtIndex(0)//在指定位置删除元素
shoppingList.removeFirst(2)//删除前几个
shoppingList.removeLast()//删除最后一个
print(shoppingList[1])//获取数组元素并输出
print("list value:\(shoppingList.count)")//输出数组个数
//数组遍历
for item in shoppingList{
print("1.遍历数组:\(item)");
}
for (var i=0;i<shoppingList.count;i++){
print("2.遍历数组:\(shoppingList[i])")
}
//定义字典
var occupations:[String:String] = [:]
//var occupations = [:]
occupations = ["Malcolm":"Captain","Kaylee":"Mechanic"]
occupations["Malcolm"] ="Public Reclations"//添加和修改字典元素都这么写
print("\(occupations["Malcolm"])\n\(occupations["Kaylee"])")
//removeValueForKey 移除字典中对应的键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的value或者在没有值的情况下返回nil
if let removeValue = occupations.removeValueForKey("Malcolm"){
print("移除的值是:\(removeValue)")
}else{
print("字典中没有对应的键值要移除:Malcolm")
}
//通过设置为nil来移除键值对
occupations["Malcolm"] ="Public Reclations"
occupations["Malcolm"] = nil
//字典的遍历
for(dicCode,dicName) in occupations{
print("\(dicCode):\(dicName)")
}
for dicCode in occupations.keys{
print("所有键:\(dicCode)")
}
for dicName in occupations.values{
print("所有值:\(dicName)")
}
//问题以下代码会报错
/*******
//定义空数组
var shoppingListErro = []
if shoppingListErro.isEmpty{
}
shoppingList[1] = "bottle of water"
错误原因:字典没有声明数据类型不能进行isEmpty的判断也不能进行赋值
改为var shoppingListErro:[String] = []
或者直接赋的有值var shoppingListErro = ["1","2","3"]
除了数组是这样,字典也是同样的
*******/