Po pierwsze, każda funkcja zwraca coś (co najmniej jest pustą krotką), nawet jeśli nie zadeklarowano żadnego typu zwrotu.
(@noreturn jest przestarzała; patrz Aktualizacja Swift 3 poniżej). Nie istnieją funkcje, które natychmiast zakończyć proces i zrobienia nie powrót do rozmówcy. Są one oznaczone Swift z @noreturn
, jak
@noreturn public func fatalError(@autoclosure message:() -> String = default, file: StaticString = #file, line: UInt = #line)
@noreturn public func preconditionFailure(@autoclosure message:() -> String = default, file: StaticString = #file, line: UInt = #line)
@noreturn public func abort()
@noreturn public func exit(_: Int32)
i nie może być więcej.
(Uwagi: podobne adnotacje istnieją w innych językach programowania lub kompilatorów, takich jak [[noreturn]]
w C++ 11, __attribute__((noreturn))
jako rozszerzenie GCC lub _Noreturn
dla kompilatora dzyń.)
Można oznaczyć własną funkcję za pomocą @noreturn
, jeśli to również bezwarunkowo kończy proces , , np., np. wywołując jedną z wbudowanych funkcji, takich jak
@noreturn func myFatalError() {
// Do something else and then ...
fatalError("Something went wrong!")
}
Teraz można korzystać z funkcji w klauzuli else z guard
stwierdzeniem:
guard let n = Int("1234") else { myFatalError() }
@noreturn
funkcje mogą być również używane do oznaczania przypadki to "nie powinno być" "i wskazywać błąd programowania.Prostym przykładem (wyciąg z Missing return UITableViewCell)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyTableViewCell
switch (indexPath.row) {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("cell0", forIndexPath: indexPath) as! MyTableViewCell
cell.backgroundColor = UIColor.greenColor()
case 1:
cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! MyTableViewCell
cell.backgroundColor = UIColor.redColor()
default:
myFatalError()
}
// Setup other cell properties ...
return cell
}
bez myFatalError()
oznaczone @noreturn
, kompilator skarżą o brakującym powrotu w przypadku domyślnego.
Update: Swift 3 (Xcode 8 beta 6) atrybutu @noreturn
zastąpiono przez typ Never
powrotnej, tak w powyższym przykładzie będzie teraz zapisana jako
func myFatalError() -> Never {
// Do something else and then ...
fatalError("Something went wrong!")
}
Zobacz: http: // stos overflow.com/questions/27829132/convincing-swift-that-a-function-will-never-return-due-to-a-thrown-exception –