0

I'm working in Swift and one of the protocols I'm using needs to return an UnsafeMutablePointer<T> of a particular object.

I have something like this:

@objc var myProperty:UnsafeMutablePointer<someObject>
{
   get
   {
      // I call a class function here to get a 'someObject' 
      // return object which I need to pass back a pointer to it. 

      return UnsafeMutablePointer<someObject>
   }
}

The problem is that Xcode doesn't like this. It complains that '>' is not a unary operator.

I've also tried removing the UnsafeMutablePointer<> and use an & in front of someObject but it complains that the & is to be used immediately in a list of arguments for a function.

I suppose I just can't find the right syntax for this? Any help would be appreciated.

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Mario A Guzman
  • 3,483
  • 4
  • 27
  • 36

1 Answers1

0

If someObject has the type SomeClass, then you need to update your declaration like this:

@objc var myProperty:UnsafeMutablePointer<SomeClass>
{
   get
   {    
      return UnsafeMutablePointer<SomeClass>(unsafeAddressOf(someObject))
   }
}

The generic argument needs to be the type of the returned data, and you also need to intialize a specialized UnsafeMutablePointer with the memory address of the desired object.

Cristik
  • 30,989
  • 25
  • 91
  • 127
  • I see what you did there. Yes, you assumed correctly. 'SomeClass' is the same type of object as 'SomeObject'. – Mario A Guzman Jan 22 '16 at 04:07
  • I tried what you did before you added the UnsafeAddressOf edit. I was getting this error: Cannot invoke initializer for type 'UnsafeMutablePointer' with an argument list of type '(AudioStreamBasicDescription)' – Mario A Guzman Jan 22 '16 at 04:07
  • Adding the 'unsafeAddressOf' gives me the following error: Argument type 'AudioStreamBasicDescription' does not conform to expected type 'AnyObject' – Mario A Guzman Jan 22 '16 at 04:09
  • @MarioAGuzman, depending on the context, you might not need such a property, especially as `UnsafeMutablePointer` is unsafe to use at later times, take a look at http://stackoverflow.com/questions/29556610/cast-a-swift-struct-to-unsafemutablepointervoid, for example – Cristik Jan 22 '16 at 07:25