Search code examples
iosswiftintuint

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.


Solution

  • “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)");
    }