clawoo
clawoo

Reputation: 791

Setting value to a property in a referenced C struct in Swift

What I am trying to do is modify the value of a C struct that I have a reference to like so:

In BridgingHeader.h:

struct info_type {
    int priority;
};

In ViewController.swift:

class MyClass {
    func viewDidLoad() {
        var info = info_type()
        info.priority = 2    
        processInfo(&info)
    }

    func processInfo(infoRef: UnsafePointer<info_type>) {
        info.memory.priority = 1
    }
}

However, the code triggers a "Command failed due to signal: Abort trap: 6" in Xcode. Opening the build output I see

Assertion failed: (GetSetInfo.getInt().hasValue()), function getSetterAccessibility, file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.0.42.3/src/swift/include/swift/AST/Decl.h, line 4070.
0  swift                    0x0000000106d17b9b llvm::sys::PrintStackTrace(__sFILE*) + 43
1  swift                    0x0000000106d182db SignalHandler(int) + 379
2  libsystem_platform.dylib 0x00007fff8eaacf1a _sigtramp + 26
3  libsystem_platform.dylib 0x00007fff5aee4bec _sigtramp + 3426974956
4  libsystem_c.dylib        0x00007fff8ef73b53 abort + 129
[...]

Am I doing something wrong or did I stumble upon an Xcode bug? I am using Xcode 7.0 beta 2 (Version 7.0 beta (7A121l))

Upvotes: 2

Views: 86

Answers (1)

Martin R
Martin R

Reputation: 539685

Since the processInfo() method modifies the memory pointed to by infoRef, the parameter must be declared as a mutable pointer:

func processInfo(infoRef: UnsafeMutablePointer<info_type>) {
    infoRef.memory.priority = 1
}

This compiles and works as expected.

Xcode 6.4 issues a proper error message for your code:

func processInfo(infoRef: UnsafePointer<info_type>) {
    infoRef.memory.priority = 1 // error: cannot assign to the result of this expression
}

but Xcode 7 beta 2 crashes, which is a bug.

Upvotes: 2

Related Questions