swift入门(语法和基本类型)
2019-12-19 本文已影响0人
Mr姜饼
语法区别
1. OC
[[UIView alloc]initWithXXX:xxx];
swift
UIView(XXX:xxx)
类名() = alloc / init 等价
2.类方法
OC [UIColor redColor]
Swift UIColor.red()
2.0 UICOlor.redColor()
3.访问当前对象的属性,可以不使用self.
建议:都不用,在编译器提示的时候,再添加,会对“语境”有更好的体会
4.没有“;”分号
5,枚举类型
OC 需要写全称 UIButtonTypeContactAdd
Swift 直接用. contactAdd
6.监听方法
OC : @selector()
Swift: #selector() 如果是带参数的话,不需要带 :
7.调试
OC:Nslog __FUNCTION__
Swift :Print(没有时间戳、更高效) #function
循环
//正序
for idx in 0..<9 {
print(idx)
}
//反序
for idx in 0..<9.reserved() {
print(idx)
}
let array = ["嚣张","哈哈","弟弟"]
for e in array.enumerated(){
print (e)
}
for [idx , value] in array.enumerated(){
print ("\(idx) \(value)")
}
for [idx , value] in array.enumerated().reserved() {
print ("\(idx) \(value)")
}
数组
let array1 = ["嚣张","哈哈","弟弟"] //不可变数组
var array2 = ["嚣张","哈哈","弟弟"] //可变数组
array2 += array1 //数组拼接
ps:必须是同种类型的数组才能进行拼接
字典
let dic1 = ["name" : "张三" , "age" : 2 ] //不可变字段
var dic2 = ["name" : "张三" , "age" : 2 , "gender" : "一年级" ] //可变字典
//将dic2拼接到dic1上
for e in dic1 {
dic2[e.key] = dic1[e.key]
}
可选项
let age : Int? = 2
let name: String? = "张三"
//此次需要解包
print ("\(age!) \(name!)")
if let
var age : Int?
let name = "张三"
//age = 2
if let oage = age {
print("\(oage)的年龄为\(oage)")
}else{
print("有一项为空")
}
guard let
var age : Int?
let name = "张三"
//age = 2
guard let zage = age else {
print("有一项为空")
return
}
print("\(zage)的年龄为\(zage)")
switch
func demo1 () {
let str = "优秀"
switch str {
case "优秀" , "良好":
print("分数肯定超过了80分")
case "及格" :
print("分数在80-60分")
case "不及格" :
print("分数不超过60分")
case "" :
break
default:
print("")
}
}
语法小练习
func demo3() -> () {
let tab = UITableView(frame: view.bounds, style: .plain)
tab.delegate = self
tab.dataSource = self
view.addSubview(tab)
tab.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
cell.textLabel?.text = "hello -- \(indexPath.row)";
cell.backgroundColor = UIColor.yellow
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}