Created
September 25, 2016 13:08
-
-
Save takasek/7d4e4f30a93b980e8ad82ec4757b01f2 to your computer and use it in GitHub Desktop.
as Anyしたstructの同一性判定がうまくいってない話。コード置いておきますね。実行するたびに結果が変わる不思議なコードです。 #CodePiece
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let aName = Notification.Name(rawValue: "a") | |
struct Struct { let id: Int } | |
extension Struct: Equatable { | |
public static func ==(lhs: Struct, rhs: Struct) -> Bool { | |
return lhs.id == rhs.id | |
} | |
} | |
NotificationCenter.default.addObserver(forName: aName, object: nil, queue: nil) { | |
print("限定しないで受け取った→", $0.userInfo![""]!) | |
} | |
let structAsAny1 = Struct(id: 1) as Any | |
let structAsAny2 = Struct(id: 2) as Any | |
let structAsAny3 = Struct(id: 3) as Any | |
// as Any とすることで、Structはan instance of an immutable classでboxingされるはず | |
// see also: https://github.com/apple/swift-evolution/blob/master/proposals/0116-id-as-any.md | |
// thanks to @ikesyo | |
NotificationCenter.default.addObserver(forName: aName, object: structAsAny1, queue: nil) { | |
print("object: Struct(id: 1) で受け取った→", $0.userInfo![""]!) | |
} | |
NotificationCenter.default.post(name: aName, object: structAsAny1, userInfo: ["": structAsAny1]) | |
NotificationCenter.default.post(name: aName, object: structAsAny2, userInfo: ["": structAsAny2]) | |
NotificationCenter.default.post(name: aName, object: structAsAny3, userInfo: ["": structAsAny3]) | |
// しかし、classの同一性判定は期待通りに働いていない。 | |
// このコードは、実行するたびに違う結果になる。謎。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment