打印可选变量

我正在尝试这些代码行


class Student {

    var name: String

    var age: Int?


    init(name: String) {

        self.name = name

    }


    func description() -> String {

        return age != nil ? "\(name) is \(age) years old." : "\(name) hides his age."

    }

}


var me = Student(name: "Daniel")

println(me.description())

me.age = 18

println(me.description())

上面的代码产生如下


Daniel hides his age.

Daniel is Optional(18) years old.

我的问题是为什么那里有可选(18),我如何才能删除可选的而只是打印


Daniel is 18 years old.


MM们
浏览 458回答 3
3回答

扬帆大鱼

您必须了解什么是可选的。许多Swift初学者认为var age: Int?,年龄是一个可能具有或没有价值的Int。但这意味着年龄是一个可选参数,它可能包含也可能不包含一个整数。在description()函数内部,您不打印Int,而是打印Optional。如果要打印Int,则必须解开Optional。您可以使用“可选绑定”解开可选:if let a = age { // a is an Int}如果确定Optional包含一个对象,则可以使用“强制展开”:let a = age!或者在您的示例中,由于您已经在description函数中测试了nil,因此您可以将其更改为:func description() -> String {    return age != nil ? "\(name) is \(age!) years old." : "\(name) hides his age."}

汪汪一只猫

出于测试/调试的目的,我经常想将可选内容作为字符串输出,而不必始终测试nil值,因此我创建了一个自定义运算符。在阅读了另一个问题的答案后,我甚至进一步改善了情况。fileprivate protocol _Optional {&nbsp; &nbsp; func unwrappedString() -> String}extension Optional: _Optional {&nbsp; &nbsp; fileprivate func unwrappedString() -> String {&nbsp; &nbsp; &nbsp; &nbsp; switch self {&nbsp; &nbsp; &nbsp; &nbsp; case .some(let wrapped as _Optional): return wrapped.unwrappedString()&nbsp; &nbsp; &nbsp; &nbsp; case .some(let wrapped): return String(describing: wrapped)&nbsp; &nbsp; &nbsp; &nbsp; case .none: return String(describing: self)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}postfix operator ~? { }public postfix func ~? <X> (x: X?) -> String {&nbsp; &nbsp; return x.unwrappedString}显然,可以根据自己的喜好调整操作符(及其属性),也可以将其设置为函数。无论如何,这使您可以编写如下的简单代码:var d: Double? = 12.34print(d)&nbsp; &nbsp; &nbsp;// Optional(12.34)print(d~?)&nbsp; &nbsp;// 12.34d = nilprint(d~?)&nbsp; &nbsp;// nil集成了其他人的协议思想后,它甚至可以与嵌套的可选对象一起使用,而嵌套可选对象通常在使用可选链接时发生。例如:let i: Int??? = 5print(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Optional(Optional(Optional(5)))print("i: \(i~?)")&nbsp; &nbsp; // i: 5
打开App,查看更多内容
随时随地看视频慕课网APP