问题描述
在Swift中,他们引入了 Type?
构造,创建一个可选类型,强制程序员检查该值是否真的存在。 / p>
此外,在Swift中没有异常处理。
但是有一个内置的可选性机制。
此可选功能?
只是一个可选< T>
c>
我想知道是否有任何传递错误的方法信息通过可选类型。
可以通过可选类型 Int?
返回错误信息,可以abc123.toInt可以替换异常或NSError?当然,Cocoa仍然使用(并将使用?)NSError模式。
在操场上玩,我在Swift的header中找到了这段代码: p>
协议可打印{
var description:String {get}
}
T? :Printable {
var description:String {get}
}
向任何可选类型添加readonly属性 description
。这将是超级强大的(可能会导致许多问题,我猜)。
但是试图扩展自己 T? c $ c>我得到一个错误:
非名义类型'T?'不能扩展
那么,为什么他们不向所有可选类型添加一个属性来携带错误信息?它不会有用吗?我的意思是,如果你想要多个返回类型,你可以返回一个元组...
/ p>
extension可选:DebugPrintable {
///self的文本表示, 。
var debugDescription:String {get}
}
So in Swift they introduced the Type?
construct, that creates an optional type which "forces" the programmer to check if the value actually exists.
Also, in Swift there is no exception handling.But there is this built-in optionality mechanism.
This optional feature ?
is just an Optional<T>
enum behind the scenes inspired from Haskell's Maybe
.
I was wondering if there was any way of passing error information through the optional type.Can "abc123".toInt()
return error information through the optional type Int?
? Could this replace Exceptions or NSError? Of course Cocoa still uses (and will use?) the NSError pattern.
Playing in the playground, I found this piece of code in the Swift "header":
protocol Printable {
var description: String { get }
}
extension T? : Printable {
var description: String { get }
}
Basically this adds a readonly property description
to ANY optional type. This would be super powerful (and could lead to many problems, I guess).
But after trying to extend myself the T?
I get an error:
Non-nominal type 'T?' cannot be extended
So why didn't they add a property to all optional types to carry with them error information? Wouldn't it be useful? I mean, you could return a tuple if you want multiple return types...
this is already part of the language
extension Optional : DebugPrintable {
/// A textual representation of `self`, suitable for debugging.
var debugDescription: String { get }
}
这篇关于可选< T>和可选类型在Swift?扩展可选用于携带错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!