你可以将一个类型化的数组传递给swift中的枚举函数吗?

时间:2015-05-15 11:52:10

标签: function swift enums arguments

在Swift应用程序中,我创建了一个带有函数的枚举,该函数将一组CLBeacon对象作为唯一的参数(即[CLBeacon])。我没有得到枚举的clang错误,但是当我尝试使用枚举时,clang抱怨我无法使用([CLBeacon])的参数列表调用该函数。这是代码:

enum BeaconArrayState {

    case NoObjectOnScreen, FirstObjectOnScreen, FirstObjectOffScreen

    mutating func check(beacons: [CLBeacon]) -> BeaconArrayState {

        switch self {

            case FirstObjectOnScreen:
                return .FirstObjectOnScreen
            case FirstObjectOffScreen:
                return .FirstObjectOffScreen
            case NoObjectOnScreen:
                if beacons.count > 0 {
                    println("push to screen associated with beacon \(beacons[0].minor)")
                }
                return .NoObjectOnScreen
        }
    }
}
var beaconArrayState: BeaconArrayState = .NoObjectOnScreen

func beaconManager(manager: AnyObject!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
    let knownBeacons = beacons.filter{$0.proximity != CLProximity.Unknown}
    //send updated beacons array to perform parseBeacons
    NSNotificationCenter.defaultCenter().postNotificationName("updateNotificationPriorities", object: knownBeacons)

    beaconArrayState = BeaconArrayState.check(knownBeacons as [CLBeacon])
}

这给出了错误 - Cannot invoke 'check' with argument list of type '([CLBeacon])'

case语句中的代码与现在无关,尚未确定,但为什么调用错误?

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是您正在静态调用check方法,而该函数根本不是静态的。另外检查函数它不是一个变异函数,所以你不需要变异关键字。为了完成这项工作,请进行以下更改beaconArrayState = beaconArrayState.check(knownBeacons as [CLBeacon]),或者如果您希望检查方法改变自身,请更改为:

mutating func check(beacons: [CLBeacon]) {

    switch self {

    case FirstObjectOnScreen:
        self = .NoObjectOnScreen
    case FirstObjectOffScreen:
        self = .FirstObjectOffScreen
    case NoObjectOnScreen:
        if beacons.count > 0 {
            println("push to screen associated with beacon \(beacons[0].minor)")
        }
        self = .NoObjectOnScreen
    }
}

然后只需调用beaconArrayState.check(knownBeacons as [CLBeacon])并且becaonArrayState将获得其新值