简体   繁体   English

无法在Swift中将Anyobject转换为NSString

[英]Fail to make Anyobject to NSString in Swift

There's an exception when I run it. 当我运行它时,会有一个例外。

self.year = value as! NSString 

Exception: 例外:

 Could not cast value of type '__NSDate' (0x1051bd6a0) to 'NSString' (0x10564d8e0).

What am I missing ? 我想念什么?

var  datePicker = ActionSheetDatePicker(title: "Date:",datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(),doneBlock: { 

   picker, value, index in

   self.year = value as! NSString 

   println("year = \(year)")
   println("value = \(value)")

   return
   }, cancelBlock: { ActionStringCancelBlock in return }, origin: sender.superview!.superview)

I think you have to convert date to string via your selected value 我认为您必须通过选择的值将日期转换为字符串

let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
let dateStr: String = formatter.string(from: value as! Date)

You can use any other format like : "yyyy" or "HH:mm:ss" etc. 您可以使用其他任何格式,例如:“ yyyy”或“ HH:mm:ss”等。

and set it to your year variable 并将其设置为您的年份变量

self.year = dateStr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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