swift可选类型
来源:互联网 发布:java算法 编辑:程序博客网 时间:2024/05/21 01:52
今天开始学习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.
}
}
- swift语言-可选类型
- Swift:可选类型(Optional)
- Swift-Optional(可选类型?!)
- swift 之可选类型
- swift之可选类型
- Swift 可选类型 ?和!
- Swift 可选类型
- swift可选类型
- Swift笔记:可选类型
- Swift - 可选类型
- Swift-可选类型
- swift可选类型
- swift-可选类型
- Swift 可选类型
- swift 可选类型语法
- Swift--05可选类型
- swift学习可选类型
- Swift 可选(Optionals)类型
- 韩国民众游行要总统下台
- Android RecyclerView (四)总结(一)-(三)并且实现下拉刷新数据,上拉加载数据功能
- 安卓使用系统提供videoview播放视频
- 主题等.ppt及活动内容.ppt文档规范要求
- hadoop 2.6.0完全分布式安装
- swift可选类型
- Linux chrome/firefox flash过期问题解决办法
- Android Fragment 从源码的角度去解析(下)
- 安卓开发 加载图片到内存
- 11月30日 && 12月2日 && 12月3日 课堂笔记
- Android实验八之图片查看器
- POJ-1698-网络流最大流构图
- 仿美图秀秀图片调色板
- css比较优秀的库