How a Swift can fly through the Objective Sea (part 1)

Derrick Ho
2 min readJan 14, 2017

The Objective-C is a very fluid entity and it will not be evaporating any time soon. While the Swift has wings that help it fly through the sky, it may occasionally dive down to the Objective-C to catch some food.

This is the start of a series of Swift and Objective-c interoperability nuggets.

Swift revealing its private code to objective-c

Swift has a private access modifier called private which means only things in its scope may use it. Objective-c has no privacy, instead it is hidden; If you know the name of the method/variable, you can access it.

Suppose we have some swift code like this:

class Mute: NSObject {
private var name = “moe”
private func sayName() -> String {
return name
}
}

Because there is no public access no one outside the class may access it.

Mute().name // Doesn't not compile

You can trade Swift’s true privacy for objective-c’s kind of privacy by adding @objc

class Mute: NSObject {
@objc private var name = “moe”
@objc private func sayName() -> String {
return name
}
}
// Called like this
m.value(forKey: "name") // "moe"
m.value(forKey: "sayName") // "moe"m.perform("sayName").takeRetainedValue() // "moe"m.performSelector(onMainThread: "sayName", with: nil, waitUntilDone: true)

Off the top of my head, you can use this strategy in the target-action pattern (aka any selector-ish APIs).

var button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))func initButton() {
self.addSubview(button)
button.addTarget(self, action: #selector(tappedButton), for: .touchUpInside)
}
@objc private func tappedButton() {
print("do stuff")
}

It also might be useful for unit testing private parts of your app.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response