简体   繁体   中英

Swift how to write statement on single line

Given the following JSON parsing code:

extension NSDictionary {

    public func toWeatherReport() -> WeatherReport {

        let city = self.valueForKeyPath("request.query") as String
        let currentConditionsDict = self.valueForKeyPath("current_condition") as NSDictionary
        let currentConditions = currentConditionsDict.toCurrentConditions()

        return WeatherReport . . etc 

    }

    public func toCurrentConditions() -> CurrentConditions {

        let summary = self.valueForKeyPath("summary")
        etc 
        return CurrentConditions . . etc
    }

}

I would prefer to write:

let currentConditions = self.valueForKeyPath("current_condition") 
    as NSDictionary.toCurrentConditions()

. . however Swift did not like that. Is there a way to write this expression on a single line?

Use parentheses.

let currentConditions = (self.valueForKeyPath("current_condition") 
as NSDictionary).toCurrentConditions()

That should solve your syntax issue, but I'm not sure all these extension methods on NSDictionary are the best design. It's hard to say what would be best without seeing more of what you're trying to do — I'd recommend asking a separate question to seek advice on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM