如何将它从Obj-C转换为Swift?

时间:2015-07-01 15:44:58

标签: objective-c swift ios8 xcode6

我正在尝试在swift中重新编写一个应用程序,该应用程序目前在Objective-C中。我如何将这一行更改为Swift,因为我当前的尝试不能证明是正确的

Tabata *tabata = [notification object];

以下是整个功能:

- (void)stateChanged:(NSNotification*)notification
{
if (enabled)
{
    Tabata *tabata = [notification object];
    switch (tabata.getState) {
        case EXERCISE:
        case RELAXATION:
            [player play];
            break;

        default:
            break;
    }
}
}

以下是我转换成Swift的内容:

func stateChanged(notifcation: NSNotification) {
    if enabled {

        var tabata: Tabata! = notification.object //error "Use of unresolved identifier 'notification'"
        switch tabata.getState() {
        case .EXERCISE: fallthrough
        case .RELAXATION:
            player.play()
            break

        default:
            break

        }
    }
}

2 个答案:

答案 0 :(得分:0)

在Swift中,你必须向下转换AnyObject类型的对象,而不是声明类型

   var tabata = notification.object as! Tabata

答案 1 :(得分:0)

func stateChanged(notification: NSNotification) {
    if(enabled) {
        var tabata: Tabata = notification.object as! Tabata
        switch tabata.getState() {
        case .EXERCISE:
            fallthrough
        case .RELAXATION:
            player.play()
            break
        default:
            break
        }
    }
}

希望这有帮助!