Issue with operator method with optionals


(Serkan Kurt) #1

I am compiling the following swift code in Fire 9.1.99.2151 for Android;

public class MyClass
{
    public private(set) var value: String
    
    public init(value: String)
    {
        self.value = value
    }
    
    public static func fromString(_ str: String?) -> MyClass?
    {
        guard let str = str else { return nil }
        
        return MyClass(value: str)
    }
    
    public func toString() -> String { return value }
}

public func == (left: MyClass?, right: MyClass?) -> Bool
{
    guard let left = left else
    {
        guard let _ = right else { return true }
        
        return false
    }
    
    guard let right = right else { return false }
    
    return left.value == right.value
}

Now this operator works fine with MyClass instances but it fails in this test case;

public func testCase()
{
    let v1 = String("111") as AnyObject
    let r1 = v1 == nil
    
    assertTrue("Expected \(v1) == nil to be false", condition: r1 == false) // This passes
    
    var d = [String: AnyObject]()
    d["TestValue"] = String("222") as AnyObject
    
    let v2 = d["TestValue"]
    let r2 = v2 == nil
    
    assertTrue("Expected \(v2) == nil to be false", condition: r2 == false) // This fails on Android!
}

It fails the test as it compiles to;

public void testCase() {
    String v1 = (String)(new String("111"));
    boolean r1 = v1 == null;
    self.assertTrue____condition(String.format("Expected %s == nil to be false", new Object[]{v1}), !r1);
    HashMap d = (HashMap)Dictionary.$New();
    String var6;
    Dictionary.setItem__$mapped____(d, "TestValue", var6 = (String)(new String("222")));
    Object v2 = (Object)Dictionary.getItem__$mapped__(d, "TestValue");
    boolean r2 = __Global.op_Equality(!(v2 instanceof MyClass)?null:(MyClass)v2, (MyClass)null);
    self.assertTrue____condition(String.format("Expected %s == nil to be false", new Object[]{v2}), !r2);
}

Surprisingly it tries to use the == operator method that we defined for MyClass even if we never used MyClass in the test case.


(marc hoffman) #2

My apologies for the delay on this. Can you send me a full project that shows this?