0
struct User: Codable,Identifiable,Hashable{
   var @DocumentID var id: String?
   var name: String
   var birthDay: Timestamp?
}



struct Profile: View {
   @Binding var user: User
   @State var birthDay: Date
   init(){
     self._birthDay = State(initialValue:  _user.wrappedValue.birthDay as! Timestamp 
   }
}

I don't know how to write the down casting from Firestore's Timestamp to Date. I got the error Cannot convert value of type 'Timestamp' to expected argument type 'Date' in self._birthDay = State(initialValue: _user.wrappedValue.birthDay as! Timestamp . If _user.wrappedValue.birthDay is nil, I want to set the current date.

I checked this But this is possible for nil. I want to set the current date if it is nil. And User's birthday is optional. So I want to set jest Date type.

I think I can write this

let timestamp = _user.wrappedValue.birthDay as! Timestamp 
let date = timestamp.dateValue()

But I don't know if the timestamp is nil how to set current date.

I tried writing the down casting. But I can't get success. Especially I don't know how to write that in 1 statement.

Taro
  • 23
  • 5
  • You can't downcast. You need to use the Timestamp `dateValue()` function, which creates a `Date` from a `Timestamp`. – Duncan C Jan 12 '23 at 16:12
  • I know I can write this `let timestamp = _user.wrappedValue.birthDay as! Timestamp let date = timestamp.dateValue()` But I don't know how to write this context like that. – Taro Jan 12 '23 at 16:14
  • `let date = (_user.wrappedValue.birthDay as? Timestamp ?? TimeStamp(date: Date())).dateValue()` should work – Duncan C Jan 12 '23 at 18:19
  • Not working. Though I already imported `Firebase` and `FirebaseFirestore` , I got the error `Cannot find 'TimeStamp' in scope` at `TimeStamp(date: Date()))` – Taro Jan 13 '23 at 18:06
  • Oh, change "Time**S**tamp" to "Timestamp". (Switch the "S" to lower case.) – Duncan C Jan 13 '23 at 18:21
  • Case matters in Swift types (as in most C-like languages.) My fingers tend to type camel case automatically, so I capitalized the "S" by mistake. – Duncan C Jan 13 '23 at 18:22
  • I changed `TimeStamp` to `Timestamp`. But I got another error `Value of type 'State' has no member 'dateValue'` in dateValue() . – Taro Jan 14 '23 at 13:16
  • That’s a SwiftUI issue. I don’t really know SwiftUI – Duncan C Jan 14 '23 at 18:32

0 Answers0