今天开始学习swift
有一个概念挺重要的也是跟OC差别比较大的
其实说白了就是指针类型 也就是说创建的类型是可以为 nil 的 类型(在这里说一下nil其实就是指针指向的内存地址为0x0的地址 另外对象的引用计数为0也等于把对象置为nil)
1.可选类型如何定义
//var name :Optional<String> = nil
var name :String? = nil
2.可选类型进行赋值
//name = Optional("hz")
name = "hz"
3.取出可选类型中的值
需要解包(可以理解为可选类型是带有Optional(")这个外包装的)
//因为可选类型是有空值的可能性的,所以解包前要验证是否为空,才可以强制解包
if name != nil{
name!
}else{
}
另一种写法
// 可选绑定
if let name1 = name {
print(name1)
}
//以下代码为写的一个tableView
import UIKit
class ViewController: UIViewController,UITableViewDataSource{
override func viewDidLoad() {
super.viewDidLoad()
// let rect :CGRect = CGRect(x:0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
let tableView:UITableView? = UITableView(frame: self.view.bounce, style: .plain)
tableView?.dataSource = self
if tableView != nil {
self.view.addSubview(tableView!)
}else{
}
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellid :String = "cellid"
var cell :UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid)
if cell == nil{
cell = UITableViewCell(style: .default, reuseIdentifier: cellid)
}
cell?.textLabel?.text = "这是第\(indexPath.row)行"
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}