21

I was wondering if you can write inline assembly in Swift.

I know that in Objective-C you could use something like this:

inline void assemblyFunc() {
    __asm__(/*Assembly*/);
}

But in Swift it seems that you can't use __asm__(/*Assembly*/).

Does anyone know how to use __asm__() if its even possible. I haven't found anything about it, so I thought it would be a good question to ask.

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
Bas
  • 4,423
  • 8
  • 36
  • 53
  • 1
    There's no inline asm support. Please report a bug if this feature is important to you. – Stephen Canon Jun 16 '14 at 15:03
  • 1
    the _Swift_ is mostly designed for the entry-level developers on iOS platform. – holex Jun 16 '14 at 15:04
  • @holex I don't think so. Swift is designed to be more expressive and make developers more productive in the cases where performance is not the number 1 priority, which is most of them – Jiaaro Jun 16 '14 at 15:16
  • 5
    Nowhere in Apple's developer or marketing materials for Swift do they say it's only or primarily for new developers. As @Jiaaro notes, it's designed to increase productivity for all developers. (And it's designed to be fast, even if it's not always so in the beta.) – rickster Jun 16 '14 at 15:20
  • "The focus of Swift 1.0 is definitely on improving general app development, but we do expect Swift to grow capabilities (e.g. perhaps even the ability to write inline assembly code)" - [Apple Developer Forums](https://devforums.apple.com/message/1007178#1007178) – griotspeak Jun 19 '15 at 23:28
  • 1
    Possible duplicate of [calling a function defined in assembly from swift](https://stackoverflow.com/questions/39420513/calling-a-function-defined-in-assembly-from-swift) – Sapphire_Brick Oct 23 '19 at 01:26
  • @Sapphire_Brick How can this question be a duplicate when it was asked before the question you linked? – Bas Oct 28 '19 at 11:21
  • then the other one is a duplicate, mark it if you wish – Sapphire_Brick Oct 28 '19 at 19:24

2 Answers2

14

To expand on what Robert Levy said, you can just use the Swift/Obj-C interop feature, and write an Obj-C class that does the ASM stuff, which you can then call from Swift.

It's an annoying workaround, but it should work nonetheless.

You can read more about how to do ObjC-to-Swift interop here

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
13

There isn't a way in Swift itself. If you need this, probably a good opportunity to take advantage of Swift-ObjC interop.

Robert Levy
  • 28,747
  • 6
  • 62
  • 94