0
votes

I have an object, let's say its called "Event". Event has several optionals.

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)."
  }
}

When I call for the description, it will return a string, and depending on if they exist or not the optional values will return nil or "Optional(Event name)". I want the option for some of the properties to be nil and return the unwrapped value if they exist.

I have looked at this option:

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."
}

This works, but for me to cover all the cases it is going to take forever. It may contain hundreds of cases.

So my question is: Is there an easier way to do this? Return nil if not available, and unwrap if it is.

Thank you!

1

1 Answers

3
votes

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).