ctietze,
@ctietze@mastodon.social avatar

Objective-C professionals around the world, I summen ye 🗺️

Is there not a way to annotate an Objective-C method that returns a Foundation type like NSString to avoid automatic bridging to Swift.String?

I really want to stay in NSString-land.

(Actually, I probably even want to keep fiddling with an NSMutableString as a mutable string)

rjmccall,
@rjmccall@hachyderm.io avatar

@ctietze If you write obj.method() as NSString in Swift, you should get the result of the call without any bridging

ctietze,
@ctietze@mastodon.social avatar

@rjmccall @nicklockwood Oh I didn't know that this would actually avoid bridging.

I'll have to double check in the profiler to make sure

nicklockwood,
@nicklockwood@mastodon.social avatar

@ctietze I think that's an easier problem - NSMutableString doesn't bridge, so if you return that it shouldn't be converted to String by default

ctietze,
@ctietze@mastodon.social avatar

@nicklockwood So many of its methods that produce substrings, for example, do bridge though :(

nicklockwood,
@nicklockwood@mastodon.social avatar

@ctietze I'm curious: if you call such a method by saying something like

mutableString.substring(…) as NSString

would Swift actually do a two-way bridging, or is the optimizer smart enough to recognize that the bridging is a no-op in that scenario?

nicklockwood,
@nicklockwood@mastodon.social avatar

@ctietze otherwise, if you control the signature to the method then there are various (slightly ugly) workarounds I can think of, such as returning NSObject and casting it on the Swift side.

ctietze,
@ctietze@mastodon.social avatar

@nicklockwood I feared as much!

My original idea was even worse, returning id, but NSObject would be somewhat better

uliwitness,
@uliwitness@chaos.social avatar

@ctietze @nicklockwood I wonder what would happen if you declared an ObjC subclass of NSString and returned that. 😈

ctietze,
@ctietze@mastodon.social avatar
nicklockwood,
@nicklockwood@mastodon.social avatar

@ctietze another option might be to create an objc protocol that mirrors the NSString API and then conform NSString to it. If you work exclusively with that protocol, Swift wouldn't know how to bridge it

ctietze,
@ctietze@mastodon.social avatar

@nicklockwood that's an interesting idea!

I stumbled upon this task in the first place by writing an extension to NSString in ObjC that produced an NSString again, which Swift immediately bridged. Didn't think of a objc-annotated protocol

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • kavyap
  • thenastyranch
  • GTA5RPClips
  • tester
  • InstantRegret
  • DreamBathrooms
  • ngwrru68w68
  • magazineikmin
  • everett
  • Youngstown
  • mdbf
  • slotface
  • rosin
  • cisconetworking
  • megavids
  • khanakhh
  • normalnudes
  • osvaldo12
  • cubers
  • tacticalgear
  • Durango
  • ethstaker
  • modclub
  • anitta
  • provamag3
  • Leos
  • JUstTest
  • lostlight
  • All magazines