美文网首页
swift学习——基础语法

swift学习——基础语法

作者: Grt婷 | 来源:发表于2016-11-18 17:56 被阅读0次

一、swift基础语法

1.变量与常量定义

//自动类型推断 var 定义变量
var str = "Hello, playground"
//let 定义常量(不能修改的量)
let name="Hello,playground"

2.数据类型定义

//字符串
let name1:String = "Lanou"
//字符
let gender : Character = "M"
//整型
let age : Int = 12
//浮点型
let height : Float = 12.2
//双精度浮点型
let height1 : Double = 12.222

3.字符串的操作

//长度
let length = name.characters.count
// 拼接
var name3 : String = name + "pin\(123)jie"
print("name=\(name3)")
//获取第几个位置
let index=name3.index(name3.startIndex,offsetBy:2)
//rang(取字符串中指定位置的值)
let student = "yangshaofeng"
let startIndex = student.index(student.startIndex,offsetBy:2)
let endIndex=student.index(student.endIndex,offsetBy:-2)
let rang = startIndex..<endIndex
student.substring(with:rang)
//插入的上面获取的位置
name3.insert(contentsOf: "charu".characters, at: index)

 // 遍历
for item in name3.characters{
    print(item)
}

//切割
var school = "jiningshifan"
let index1 = school.index(school.startIndex,offsetBy:2)
let newSchool=school.substring(to: index1)
print(newSchool)

4.数组操作

//定义数组
var arr = [1,2,3]
var arr1 : [Int] = [Int]()

//增加元素
arr1.append(2)

//删除元素
let element = arr1.remove(at: 0)
//更新元素
arr[1] = 22
print(arr)
// 遍历
for item in arr {
   print(item)
}
for item in 0..<arr.count {
   print(arr[index])
}
for (index,item) in arr.enumerated(){
   print("index=\(index)  item=\(item)
}

5.字典操作

var dic: [Int: Int] = [1:1,2:2]

//添加,更新
dic[1] = 2 //更新
dic[3] = 3 //添加
//删除
dic.removeValue(forKey:1)
print(dic)

相关文章

网友评论

      本文标题:swift学习——基础语法

      本文链接:https://www.haomeiwen.com/subject/tghspttx.html