-2

我有这样的方法。

func getFirstDayX(date:Date)->CGFloat
{
   // let date = NSDate()
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat  = "EEEE"//"EE" to get short style
    guard let dayInWeek = dateFormatter.string(from: (date as? Date)!) else
    {
        return 0.0
    }//"Sunday"
    let dayX:CGFloat!
    print("day in week-------\(dayInWeek)")
    switch dayInWeek {
    case "Monday":
        dayX=0.0
    case "Tuesday":
        dayX=lblDayName.frame.size.width
    case "Wednesday":
        dayX=lblDayName.frame.size.width*2
    case "Thursday":
        dayX=lblDayName.frame.size.width*3
    case "Friday":
        dayX=lblDayName.frame.size.width*4
    case "Saturday":
        dayX=lblDayName.frame.size.width*5
    case "Sunday":
        dayX=lblDayName.frame.size.width*6
    default:
        dayX=0.0
    }

    return dayX
}

但我收到一个错误

条件绑定的初始化程序必须具有可选类型,而不是“字符串”

这会是什么原因?请帮我。

更新

这是我添加语言环境和保护条件之前的方式。请检查这个。

func getFirstDayX(date:Date)->CGFloat
{

let dateFormatter = DateFormatter()

dateFormatter.dateFormat  = "EEEE"//"EE" to get short style
 let dayInWeek = dateFormatter.string(from: date as Date) else

let dayX:CGFloat!
print("day in week-------\(dayInWeek)")
switch dayInWeek {
case "Monday":
    dayX=0.0
case "Tuesday":
    dayX=lblDayName.frame.size.width
case "Wednesday":
    dayX=lblDayName.frame.size.width*2
case "Thursday":
    dayX=lblDayName.frame.size.width*3
case "Friday":
    dayX=lblDayName.frame.size.width*4
case "Saturday":
    dayX=lblDayName.frame.size.width*5
case "Sunday":
    dayX=lblDayName.frame.size.width*6
default:
    dayX=0.0
}

return dayX

}

4

3 回答 3

2

您的错误已在其他答案中进行了解释。但是,让我提出一个更简单的解决方案,因为使用当天的名称来获取索引只是愚蠢的太复杂。您根本不需要日期格式化程序,只需直接询问工作日!

func getFirstDayX(date: Date) -> CGFloat {
    // Sunday = 0, Monday = 1 ... Saturday = 6
    let weekday = Calendar.current.component(.weekday, from: date)
    // Monday = 0, Tuesday = 1, ... Sunday = 7
    let weekdayIndex = (weekday + 6) % 7

    return lblDayName.frame.size.width * weekdayIndex
}
于 2017-08-19T18:40:41.700 回答
2

两个错误:

守卫让dayInWeek = dateFormatter.string(来自:(日期为?日期)!)否则

  1. string(from:date 总是返回一个非可选的。可选绑定只能用于可选项
  2. 您将一个非可选参数传递Date给一个可选Date参数,然后立即展开它是荒谬的多余。

写吧:

    let dayInWeek = dateFormatter.string(from: date)
于 2017-08-19T18:01:31.030 回答
1

守卫让...

当你写

guard let dayInWeek = [OPTIONAL_EXPRESSION] else { return 0.0 }

[ OPTIONAL_EXPRESSION]应该是一个返回可选值的表达式。

但在你的情况下,你确实写了

dateFormatter.string(from: (date as? Date)!)

它总是返回一个String.

所以没有必要使用guard let构造。

(date as? Date)!而且也不需要写

解决方案

简单地写

let dayInWeek = dateFormatter.string(from: date)
于 2017-08-19T18:01:48.357 回答