问题
My code takes an NSDate and reads year, month, and day, then strings them together as a single integer. I next want to convert this Int to a String, so that it can be inserted into a URL String, but without success:
let calendarUnits: NSCalendarUnit = .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear
let components = NSCalendar.currentCalendar().components(calendarUnits, fromDate: dateToBeExamined)
var dateInt = components.year
dateInt += components.day
dateInt += components.month
var dateString = dateInt as! String
I have tried several methods, including the following:
"\(dateInt)"
dateInt.description
dateInt as String
String(dateInt)
However, all of them tell me that "Int is not convertible to String", or, with an "!" after the "as", that "Int cast to String will always fail". Does anyone have a way around this?
回答1:
Your first - several - attempt is correct
let dateString = "\(dateInt)"
or the "sophisticated" version
let dateString = String(stringInterpolationSegment: dateInt)
Edit: but you might want to concatenate the string values rather than performing a mathematical addition, then use the syntax of the answer of zaph.
回答2:
let dateString = "\(components.year)\(components.day)\(components.month)"
println("dateString: \(dateString)")
Output:
dateString: 2015118
or
let dateString = String(components.year) + String(components.day) + String(components.month)
来源:https://stackoverflow.com/questions/31948226/converting-date-components-integer-to-string