我有这样的功能:我显然有一个可选的在我的代码,但是编译器认为我没有
func getTodaysDate() -> (day: String, date: String) {
let currentDate = Date()
let monthFormatter = DateFormatter()
let dayFormatter = DateFormatter()
monthFormatter.dateFormat = "MMMM"
monthFormatter.locale = Locale(identifier: "en_US")
let month = monthFormatter.string(from: currentDate)
dayFormatter.dateFormat = "EEEE"
dayFormatter.locale = Locale(identifier: "en_US")
let dayToday = dayFormatter.string(from: currentDate)
let calendar = Calendar.current
let dateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.day], from: currentDate)
let day = String(describing: dateComponents.day)
let date = ("\(month) \(day!)")
return (day: dayToday.uppercased(), date: date.uppercased())
}
应返回:
周五4月21日
但代之它返回:
FRI DAY,APRIL可选(21)
我不明白,因为常数'天'不是可选的。甚至当我尝试解开它的编译器抱怨说,它
不能强迫非可选类型“字符串”的展开值
有没有人一个想法是怎么回事?
是不是'dateComponents.day'选项?如果在字符串初始值设定项中使用可选项,将会遇到可怕的“可选”字面值。在String初始值设定项中使用它之前解包此属性。 – Moritz
埃里克说什么,你需要的是一个 '如果让dayAsInt = dateComponents.day {...}' 因为.day是可选的,请参阅https://developer.apple.com/reference/foundation/ datecomponents/1779808-day – muffe
'String(描述:dateComponents.day)'不打开可选项,它只是打印调试描述 – redent84