Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active June 16, 2018 16:30
Show Gist options
  • Save KentarouKanno/d3f709a732f7bf5abf62ecfe751b79b4 to your computer and use it in GitHub Desktop.
Save KentarouKanno/d3f709a732f7bf5abf62ecfe751b79b4 to your computer and use it in GitHub Desktop.

SwiftでObjective-Cの黒魔術ってどうなった?

import UIKit

var imageDebugStringKey: UInt8 = 0

extension UIImage {
    var debugString: String {
        get {
            return objc_getAssociatedObject(self, &imageDebugStringKey) as? String ?? ""
        }
        set {
            objc_setAssociatedObject(self, &imageDebugStringKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        let img1 = UIImage(named: "img")!
        img1.debugString = "画像1"
        let img2 = UIImage()
        img2.debugString = "画像2"

        print(img1.debugString)
        print(img2.debugString)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment