swift可选类型

今天开始学习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.
    }


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值