Swift-可选型

  1. 可选型的声明
var errorCode: String? = "404" //表示变量可以为空值,通常用var声明
print(errorCode) // 输出:optional("404")
  1. 可选型的基本用法
"The errorCode is " + errorCode //报错,可选型不能直接使用
需要用解包(unwrapped)的方式使用

"Hello" + errorCode! //强制解包,有风险性(errorCode可能为nil)

if let errorCode = errorCode { // 推荐用法(“if-let式”解包,建立新的解包常量,可以在大括号内持续使用)
    print("The errorCode is " + errorCode)
}  // 输出: The errorCode is 404

//一次性解包多个变量
if  let errorCode = errorCode ,
    let errorMessage = errorMessage , errorCode == "404"{
        print("Page Not Found!")

//可选型链
errorCode?.uppercased() //安全解包?
var uppercasedErrorCode = errorCode?.uppercased() //仍然是可选型

//可选型变量赋值给另一个变量
let errorCode1 = errorCode == nil ? "Error!" : errorCode!
let errorCode2 = errorCode ?? "nil-Error!"  //更简洁的写法
}
  1. 可选型更多用法
// 区别下列3中可选型
var error1: (errorCode: Int, errorMessage: String?) = (404, "Not Found")
var error2: (errorCode: Int, errorMessage: String)? = (404, "Not Found")
var error3: (errorCode: Int, errorMessage: String?)? = (404, "Not Found")

//可选型在实际项目中的应用
var ageInput: String = "16"

//隐式可选型
var errorMessage: String! = nil
errorMessage = "Not Found"
print("The message is " + errorMessage)
  1. 隐式可选型的用例
//1. 可以存放nil,可以直接使用,不用强制解包
//2. 常用于类的定义中(一开始设置为nil,在初始化后赋值)

var errorMessage: String! = nil
errorMessage = "Not Found"
"The message is " + errorMessage //但是如果是nil,则会直接报错(不安全)



class City {
  let cityName: String
  var country: Country
  init(cityName: String, country: Country) {
    self.cityName = cityName
    self.country = country
  }
}

class Country {
  let countryName: String
  var capitalCity: City! //初始化Country需要先初始化City
  init(countryName: String, capitalCity: String) {
    self.countryName = countryName
    self.capitalCity = City(cityName: capitalCity, country: self)    
  }
  func showInfo() {
    print("This is \(countryName)")
    print("The capital is \(capitalCity.cityName)")
  }
}
let china = Country(countryName: "中国", capitalCity: "北京")

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 可选型作为swift语言中一大亮点,也是非常重要的一个概念,为此我们要学好swift,就要把可选型学好。 什么是可...
    雷晏阅读 3,398评论 0 4
  • swift 边学边忘.在工作中使用的oc.真是费劲啊.这次好好做个笔记,忘了回来翻翻~学习方法:是看慕课网的视频,...
    司马捷阅读 2,372评论 0 1
  • 变量或常量在某些情况下可能表示的是未被赋值的情况,若直接不对某一类型的变量赋值,会提示该变量未初始化不可用。这时就...
    水止云起阅读 3,126评论 0 0
  • 1.什么是可选(Optionals)类型 Swift 的可选(Optional)类型,用于处理值缺失的情况。可选表...
    XieHenry阅读 4,455评论 0 0
  • Optional Chaining 与 Nil Coalesce 操作 optional chaining 对象?...
    阿黎转呀转阅读 2,593评论 0 1

友情链接更多精彩内容