我試圖從guide獲取兩個日期的時差。我不知道該怎麼投入dateComponents
的論點。當我在[.hour, .minute]
直接傳遞,我得到一個錯誤:在Swift中獲取時差3
Playground execution failed: error: MyPlayground.playground:10:46: error: type of expression is ambiguous without more context
let timeDifference = calendar.dateComponents([.hour, .minute], from: stopTime!, to: date!)
^~~~~~~~~~~~~~~~
```
我試圖將其聲明爲一個常數第一,但我不能確定是什麼類型。參數的類型爲Set<Calendar.Component>
,但是當我試圖說明它是Component
,DateComponent
或CalendarComponent
時,出現錯誤。
````
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "hh:mm a "
let time = "12:03 pm"
let stopTime = timeFormatter.date(from: time)
let date = Date()
let calendar = Calendar.current
let components:[DateComponent] = [.hour, .minute]
let timeDifference = calendar.dateComponents(components, from: stopTime!, to: date!)
您無需顯式創建'Set'。嘗試在代碼中用'[.hour,.minute]'替換'Set (components)'。 –
OOPer
哦,是的!我從來不知道'''''也可以表示一個'Set'。 @OOPer – Sweeper
請注意,OP的問題是由'date!'中的'!'引起的。 – OOPer