swiftlinuxperfect

Using 'Any' and 'AnyObject' types in Swift Linux gives errors


I have this line of code:

produceJSONMessage(message: message as AnyObject)

That works ok in XCode (Mac). However building it in linux using swift build produces an error:

/home/ubuntu/x/x/objects.swift:x:x: error: 'Any' is not convertible to 'AnyObject'; did you mean to use 'as!' to force downcast?

produceJSONMessage(message: message as AnyObject)

So I followed its advice by using produceJSONMessage(message: message as! AnyObject). It doesn't throw an error during build, but it crashes during runtime with:

Could not cast value of type 'Any' (0x9aab88) to 'Swift.AnyObject' (0x7f7c84007c88).

Anyway I got it to build and not throw an error with:

produceJSONMessage(message: message as? AnyObject)

The new problem is that when the function receives the object, it is always nil (it is not nil before entering the function). This is the function signature:

func produceJSONMessage(message: AnyObject? = nil)

Where message is usually a of String:Any type or a plain String

Anything that I should take note of here? All combinations of the codes I posted work fine for Mac XCode.


Solution

  • I made it work by removing AnyObject from my code above and replacing them with Any. Maybe I misused the AnyObject type, but it didn't help that it built ok in Mac but not in Linux!