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

结论: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
posted @ 2018-04-03 16:21  zzfx  阅读(205)  评论(0编辑  收藏  举报