2016-08-06 17 views
0

Ich versuche, einen besseren Weg zu finden, Gleichheit zu testen. Was ich nicht mag, ist der Teil mit profileImage."Bessere" Möglichkeit, Gleichheit für Optionals zu schreiben

Gibt es einen schöneren Weg, es zu schreiben?

class CustomObject : NSObject , NSCoding { 
    var pattern : String 
    var name : String 
    var id : String 
    var profilePicture : NSImage? 

    override func isEqual(object: AnyObject?) -> Bool { 
     if let other = object as? CustomObject { 
      if (id == other.id && 
       name == other.name && 
       pattern == other.pattern) { 
        if (profilePicture == nil && other.profilePicture == nil) { 
         return true 
        } else { 
         return profilePicture!.isEqual(other.profilePicture) 
        } 
      } 
     } 
     return false 
    } 
} 
+0

Nur 'profilePicture == other.profilePicture sollte funktionieren, vergleichen [wie zwei optionale NSArrays in Swift vergleichen] (http://stackoverflow.com/questions/28307242/how-to-compare-two-optional-nsarrays -in-swift). –

Antwort

2

Wenn Sie fast die gleiche implementieren möchten, wie Sie haben meine beste Empfehlung == Operator gezeigt, verwendet. (Nicht ===, nicht zu verwechseln.)

== hat eine Überlastung für Optionals mit dieser Unterschrift: (in Swift 2)

@warn_unused_result 
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool 

Und sein detaillierten Verhalten ist wie folgt:

(1) wenn lhs == null & & rhs == null, return true

(2), wenn lhs == null & & rhs! = nil, return false

(3), wenn lhs! = Nil & & rhs == null, return false

(4), wenn lhs! = Nil & & rhs! = Nil, Rückkehr (linke Skala! == rhs!)

Und im Fall # 4, nicht optionale Version von == Operator für zwei NSObject Argumente, ruft nur intern isEqual: Methode.

So CustomObject.isEqual(_:) kann als so etwas wie folgt geschrieben werden:

override func isEqual(object: AnyObject?) -> Bool { 
    if let other = object as? CustomObject { 
     return id == other.id && 
      name == other.name && 
      pattern == other.pattern && 
      profilePicture == other.profilePicture 
    } 
    return false 
} 

(. Ihre NSImage.isEqual(_:) Werke Unter der Annahme, wie erwartet)


By the way, Ihre Original-Code in einem bestimmten abstürzen Bedingung.

   if (profilePicture == nil && other.profilePicture == nil) { 
        return true 
       } else { 
        return profilePicture!.isEqual(other.profilePicture) 
       } 

Wenn profilePicture == null & & other.profilePicture! = Null, geht die Steuerung bis zum else Teil und profilePicture! abstürzen.

+0

Danke, hat das nicht durch Unit-Test abgedeckt. +1 –

Verwandte Themen