What's the difference between Optional<T> and optional types in Swift? Extending Optional to carry error information?

 ̄綄美尐妖づ 提交于 2019-12-06 06:11:45

this is already part of the language

extension Optional : DebugPrintable {

    /// A textual representation of `self`, suitable for debugging.
    var debugDescription: String { get }
}

Option in swift is like Option in Scala (Maybe in Haskell): It represents a value that may be absent.

What you're looking for is something like the Try or the Either monads from Scala, which represent two possible states of a computation, typically a Success or a Failure.

This would be a different algebraic data type, beyond the purpose of an optional value.

Ultimately, since swift doesn't have full-fledged monads in the standard library, I think the default error handling pattern will stay the classic Cocoa NSError one.

Optionals basically allow you to check whether or not a variable is nil. It's not meant to have an error message. For example take this Objective-C snippet:

if(self.someProperty == nil){
    self.someProperty = [[PropertyClass alloc] init]
}else{
    //property is not nil.
}

In swift you would do something like this:

var someProperty : PropertyClass?
if(someProperty){
    //property is not nil 
}else{
    //property is nil.
}

The apple docs say:

Optional chaining in Swift is similar to messaging nil in Objective-C, but in a way that works for any type, and that can be checked for success or failure.

newacct

Per this answer, the correct syntax is:

extension Optional : Printable {
    //...
}

Optional<T> is the definition of Optionals (see below). Type? is just the syntactic sugar for creating the type.

enum Optional<T> {
  case None
  case Some(T)
}

From the Swift Programming Language iBook, the two declarations below are equivalent

var optionalInteger: Int?
var opTionalInteger: Optional<Int>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!