Optional是以enum和泛型为基础的高阶类型

本文深入探讨了Swift中Optionals的概念及用法,包括如何通过检查和条件性地解包Optionals来确保代码的安全性。此外,还介绍了Optionals在布尔上下文中的应用,并通过具体的示例说明了Optionals的声明和初始化。
摘要由CSDN通过智能技术生成

结论:1、optionals使用时需要检查;2、可以通过!+赋值语句转化为非optionals。

 

Optional-Generic Enumeration

enum Optional<T> : LogicValue, Reflectable {
   case None
   case Some(T)
   init()
   init(_ some: T)
 
   /// Allow use in a Boolean context.
   func getLogicValue() -> Bool
 
   /// Haskell's fmap, which was mis-named
   func map<U>(f: (T) -> U) -> U?
   func getMirror() -> Mirror
}
 

A type that represents either a wrapped value or nil, the absence of a value.

 

The types of shortForm and longForm in the following code sample are the same:

let shortForm: Int? = Int("42")

let longForm: Optional<Int> = Int("42")

 

Optionals

?!

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

 

optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist.

 

  1. let possibleString: String? = "An optional string."
  1. let possibleString: String? = "An optional string."
  2. let forcedString: String = possibleString! // requires an exclamation mark

转载于:https://www.cnblogs.com/feng9exe/p/8709210.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>