Используя Swift 2, в моем надуманном примере я преобразовываю String
в Int
или, точнее, Int
или Int?
, используя универсальный. В случае, когда Int?
должно быть равно нулю, приведение завершится ошибкой с фатальной ошибкой: fatal error: unexpectedly found nil while unwrapping an Optional value
Похоже, что они могут быть похожими/повторяющимися вопросами:
Мой вопрос: как можно выполнить приведение к необязательному параметру, который равен нулю?
Пример:
class Thing<T>{
var item: T
init(_ item: T){
self.item = item
}
}
struct Actions{
static func convertIntForThing<T>(string: String, thing:Thing<T>) -> T{
return convertStringToInt(string, to: T.self)
}
static func convertStringToInt<T>(string: String, to: T.Type) -> T{
debugPrint("Converting to ---> \(to)")
if T.self == Int.self{
return Int(string)! as! T
}
// in the case of "" Int? will be nil, the cast
// here causes it to blow up with:
//
// fatal error: unexpectedly found nil while unwrapping an
// Optional value even though T in this case is an Optional<Int>
return Int(string) as! T
}
}
func testExample() {
// this WORKS:
let thing1 = Thing<Int>(0)
thing1.item = Actions.convertIntForThing("1", thing: thing1)
// This FAILS:
// empty string where value = Int("")
// will return an Optional<Int> that will be nil
let thing2 = Thing<Int?>(0)
thing2.item = Actions.convertIntForThing("", thing: thing2)
}
testExample()
nil
, но тогда компилятор жалуется, что nil несовместим с возвращаемым типомT
. Однако в случае, когдаT
равноInt?
, допустимым значением будетnil
. - person AJ Venturella   schedule 26.08.2015Optional<T>.None
. - person matt   schedule 26.08.2015return Optional<Int>.None as! T
он взорвется... Я думаю, что ваш последний комментарий, вероятно, попал в самую точку. Необязательные дженерики проблематичны. Та же фатальная ошибка,fatal error: unexpectedly found nil while unwrapping an Optional value
- person AJ Venturella   schedule 26.08.2015NilLiteralConvertible
. Поэтому, когда я делаю это gist.github.com/aventurella/dd67b6394c87d5551e74, он не терпит неудачу. В основном обеспечивает ограничение наT where T: NilLiteralConvertible
- person AJ Venturella   schedule 26.08.2015