简体   繁体   中英

Once again: Not convertible to UInt8

I like Swift, but its number type conversion quirks are starting to drive me mad... Why ist the following code resulting in a LogLevel is not convertible to UInt8 error (in the if statement)?

import Foundation;

enum LogLevel : Int
{
    case System = 0;
    case Trace = 1;
    case Debug = 2;
    case Info = 3;
    case Notice = 4;
    case Warn = 5;
    case Error = 6;
    case Fatal = 7;
}

class Log
{
    struct Static
    {
        static var enabled:Bool = true;
        static var filterLevel:LogLevel = LogLevel.System;
    }

    public class func trace(data:AnyObject!)
    {
        if (Static.filterLevel > LogLevel.Trace) {return;}
        println("\(data)");
    }
}

LogLevel of type Int should after all be equal to LogLevel of type Int.

“Enumerations in Swift are first-class types in their own right.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329

So, an enumeration is not an int and it doesn't make sense to perform mathematical comparisons on it. You have associated raw values with your enumeration values so you need to use the toRaw and fromRaw functions to access the raw values.

public class func trace(data:AnyObject!)
{
    if (Static.filterLevel.toRaw() > LogLevel.Trace.toRaw()) {return;}
    println("\(data)");
}

From the Swift book :

Use the toRaw and fromRaw functions to convert between the raw value and the enumeration value.

In your case:

if Static.filterLevel.toRaw() > LogLevel.Trace.toRaw() {
    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM