0

我有一个对象,假设它称为“事件”。事件有几个选项。

struct Event {
var name: String!
var location: String?
var attendees: [String]?
var dresscode: String?
var startDate: NSDate!
var endDate: NSDate?

var description: String {
    return "Name: \(name). Location: \(location). Attendees: \(attendees). Dresscode: \(dresscode). Start date: \(startDate). End date: \(endDate)."
  }
}

当我调用描述时,它将返回一个字符串,并且取决于它们是否存在,可选值将返回 nil 或“可选(事件名称)”。我希望某些属性的选项为 nil 并返回未包装的值(如果存在)。

我看过这个选项:

var description: String {

    switch (location, attendees, dresscode, endDate) {
        //All available
    case let (.Some(location), .Some(attendees), .Some(dresscode), .Some(endDate)):
        return "Name: \(name). Location: \(location). Attendees: \(attendees). Dresscode: \(dresscode). Start date: \(startDate). End date: \(endDate)."
    case let (.None, .Some(attendees), .Some(dresscode), .Some(endDate)):
        return "Name: \(name). Location: Not Set. Attendees: \(attendees). Dresscode: \(dresscode). Start date: \(startDate). End date: \(endDate)."
    default: return "Something."
}

这行得通,但对我来说,要涵盖所有情况,这将需要永远。它可能包含数百个案例。

所以我的问题是:有没有更简单的方法来做到这一点?如果不可用则返回 nil,如果可用则 unwrap。

谢谢!

4

1 回答 1

3

You’re in need of the nil-coalescing operator, ??:

// s will be Not Set if name == nil, 
// unwrapped value of s otherwise
let s = name ?? "Not set" 

You can then use that inside the string interpolation:

var description: String {
    let notSet = "Not set"
    let attendeesString = attendees.map { ",".join($0) }

    return "Name: \(name ?? notSet). Location: \(location ?? notSet). Attendees: \(attendeesString ?? notSet). Dresscode: \(dresscode ?? notSet). Start date: \(startDate ?? notSet). End date: \(endDate ?? notSet)."
}

Two things to note - you can’t put quotes in string interps so you have to create a notSet variable (of course, you can use multiple different default values depending on your need). And you can’t use arrays in them either so need to convert the array to a string (in this case by joining entries with a comma – that other map is optional map – if the array is non-nil, return an optional string, otherwise nil).

于 2015-01-29T11:43:47.623 回答