Swift Compiler Error when accessing array - Exit code 254 - swift

I am quite new to swift and got a pretty weird compiler error:
Command
/Applications/Xcode6-Beta5.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
failed with exit code 254
The Error occours when I ad the following lines to my code:
var response = HoopsClient.instance().collections["posts"]
response = response["_id"]
when I remove the second line everything compiles fine. I don't get it ^^
edit: The reason is probably that "response" is of type "AnyObject" according to the compiler... but shouldn't that be detected by xcode or give me a runtime error instead of this compiler error?

Try casting response as the type you're expecting. From what you're trying to do, instance().collections I would assume that it should return some type of dictionary.
var response = HoopsClient.instance().collections["posts"] as NSDictionary
That way, response now can handle subscripts so you could now (in theory) do:
response = response["_id"]
However
The error you get is regarding bad access to an array. This makes me think that instance().collections actually returns an array of some sort, containing Post objects.
Arrays in Swift can only handle Integer subscripts. If you want to access the information of a Post in the array, you can do something like this:
for post: Post in response {
println(post._id)
}
I know this is a long shot, but hope it helps.

Swift tends to throw error when it cant infer the type of an object, what you could probably do is add a conditional cast as follows
Im assuming that HoopsClient.instance().collections["posts"] is either a Dictionary or an Array
var response = HoopsClient.instance().collections["posts"]
if response is NSArray {
let item = response.objectAtIndex(0)
let reponseId: Post = item
}
if response is NSDictionary {
let item = response.objectForKet("_id")
let reponseId: Post = item
}
Any way, in my experience you should try to cast your variables when assigning from types that return AnyObject, xcode doesn't handle very well type inferring and when it's unable to infer the type the interface starts to throw error, like text editor uncoloring the code.

Related

Casting an Int as a String from a Realm result Swift

I am asking this hesitantly as I know this is probably a dumb question.
I am returning a Realm result and then have gone ahead and tried to cast it to a String as normal (to put in a text label).
However I'm getting an error 'init' has been renamed to 'init(describing:)'.
When I try use the describing method instead, the label prints "Optional" inside it which obviously isn't what I want.
Is there a reason I can't use :
previousTimeLabel.text = String(lastRecord?.time)
I'm sure I've done this before and it's been fine, am I missing something? (lastRecord.time is an Int).
I've checked the answer here about Interpolation Swift String Interpolation displaying optional? and tried changing to something like this :
if let previousRounds = String(lastRecord?.rounds) {
previousRoundsLabel.text = previousRounds
}
but get the same error + Initializer for conditional binding must have Optional type, not 'String'
The issue isn't String(lastRecord?.time) being Optional. The issue is lastRecord being Optional, so you have to unwrap lastRecord, not the return value of String(lastRecord?.time).
if let lastRecord = lastRecord {
previousRoundsLabel.text = "\(lastRecord.time)"
}
To summarize Dávid Pásztor's answer, here's a way you can fix it:
previousTimeLabel.text = String(lastRecord?.time ?? 0)
This may not be the best way for your application. The point Dávid was making is that you need to deal with lastRecord possibly being nil before trying to pass its time Int into the String initializer. So the above is one simple way to do that, if you're ok with having "0" string as your previousTimeLabel's text if there was no lastRecord.

Swift: can not invoke method with correct arguments?

I am trying to find a count of entities which satisfy predicate. According to documentation and "header" files, this should work:
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "FileRecord")
let ctx: NSManagedObjectContext = GetCtx()
let res = try ctx.count(for: fetch)
however I get compile error:
Cannot invoke 'count' with an argument list of type '(for: NSFetchRequest<NSFetchRequestResult>)'
however when I create the fetch request from FileRecord like this instead:
let fetch: NSFetchRequest<FileRecord> = FileRecord.fetchRequest()
I get the following error:
Cannot convert value of type 'NSFetchRequest<FileRecord>' to expected argument type 'NSFetchRequest<NSFetchRequestResult>'
Please anyone got an idea what can be wrong? I am a decent C++ language lawyer but I am just a novice with Swift...
EDIT: SOLVED
My example above was wrong. In reality I had code functionally identical to:
let res: UInt64 = try ctx.count(for: fetch)
since count returns Int, the function did not match. The error message was not specific enough for me to see it immediately. Thanks to all who have tried to help :)

Converting a string to a class in Swift

I am using Alamofire to make a GET request and am using the ObjectMapper library to convert the response into its own class in Swift.
Alamofire.request(self.REST_METHOD!, self.REQUEST_URL, headers : ["Authentication_Token" : authToken]).responseJSON { response in
if response.response != nil && response.response?.statusCode == 200 {
let json = JSON((response.result.value as? NSDictionary)!)
let classType : AnyObject.Type = NSClassFromString(entityType)! as AnyObject.Type
//let model = Mapper<classType>.map(json.rawString())
}
}
The entityType variable can be one of many types i.e. User, Student, Teacher, Staff, etc. I am trying to dynamically create a class type and create the model based on that.
However it crashes on the line let classType : AnyObject.Type = NSClassFromString(entityType)! as AnyObject.Type giving the error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
Also when I uncomment the line let model = Mapper<classType>.map(json.rawString()), it gives me a compiler error:
classType is not a type
What is wrong with the above code
You're getting the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Because NSClassFromString is failing and returning nil, which then you are unwrapping, thereby causing the error.
I'm guessing that entityType contains a class name along the lines of myClass. Swift now uses namespaces, so to create a class from a string, the string must contain AppName.myClass.
You could either hardcode your app name, or use the following code to get it:
NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
There are other problems with your code too. When NSClassFromString succeeds, it will create an instance of the class. This cannot be cast to a type. Also, you can't pass a variable as a generic in Mapper<classType>, as Swift needs to know the class type at compile time. Instead you could change the Mapper class to take the type as a parameter. For example:
Mapper.map(classInstance.dynamicType, json.rawString())
Although now that I re-read your question, you're using a library for Mapper, and are therefore probably reluctant to change it.
And looking at the doco for ObjectMapper, it needs you to create a Mapper instance - ie. instead of Mapper<MyClass>.map you need Mapper<MyClass>().map.

How to Write Generic Function in Swift?

I'm trying to write a general argmin function in Swift. Here is my code:
func argmin<X, Y:Comparable, R:SequenceType, where X== R.Generator.Element>
(f:(X)->Y, domain:R)->X{
var gen = domain.generate()
var best = gen.next()!
var minval = f(best)
while let this = gen.next() {
let value = f(this)
if value < minval {
best = this
minval = value
}
}
return best
}
I get the error message "Expected identifier to name generic parameter" when I try to compile this definition. I have no idea what this means. It sounds like an error one would get on calling the function, not defining it, but even then, I wouldn't understand it.
I'm just starting to learn Swift. Can you explain this message? (BTW, I know this function will blow up if called with an empty sequence. I'm not worrying about that yet.)
You have to remove this comma:
func argmin<X, Y:Comparable, R:SequenceType, where X== R.Generator.Element>
^
Placed that, it tells the compiler there's another generic parameter. The error message just says that - maybe in a cryptic way, but once you know, it's clearer what it means

Recasting 'UnsafePointer<Void>' to 'CFHTTPMessageRef'

I've tried dozens of things to get this right and just can't come up with anything that works. Can anyone tell me what's wrong with the following Swift code:
let incomingRequest: CFHTTPMessageRef? = CFDictionaryGetValue(self.incomingRequests as CFMutableDictionaryRef, unsafeAddressOf(incomingFileHandle!)) as CFHTTPMessageRef
The code above gives the error message: 'UnsafePointer<Void>' is not convertible to 'CFHTTPMessageRef'
I guess what I don't understand is how do I convert an 'UnsafePointer' returned by a Core Foundation function to the pointer type it should be (i.e. CFHTTPMessageRef in this case). How do I find documentation on how to do this. I've read everything I can find, but nothing so far explains how to recast return values to what they should have been in the first place. This has to be documented somewhere, doesn't it?
EDIT
Here's the code I'm having trouble with:
let incomingRequest = CFDictionaryGetValue(self.incomingRequests as CFMutableDictionaryRef, unsafeAddressOf(incomingFileHandle!))
unsafeBitCast(incomingRequest, CFHTTPMessageRef.self)
if (incomingRequest != nil) {
let success: Boolean = CFHTTPMessageAppendBytes(incomingRequest as CFHTTPMessageRef, unsafeAddressOf(data!.bytes) as UnsafePointer<UInt8>, data!.length)
if success { // Do something... }
The CFHTTPMessageAppendBytes call still gives a "Type 'UnsafePointer' does not conform to protocol 'AnyObject'". And the following 'if' check for 'success' complains that "Type 'Boolean' doesn not conform to protocol 'BooleanType'". What the heck is that about? Boolean isn't a Boolean type?
I find the strict type checking of Swift extremely frustrating. So far it is far more difficult to code in than Obj-C, C, or any of the other languages I've used. I'm sure it's because I just don't get it, or haven't found the right documentation, but this is really driving me crazy.
Use unsafeBitCast. As following example:
import Foundation
var x = "1"
var dict : NSMutableDictionary = [x: "2"]
var y = CFDictionaryGetValue(dict as CFMutableDictionaryRef, unsafeAddressOf(x))
let str: NSString = unsafeBitCast(y, NSString.self)
str == "2"
FYI: There is one quora related with unsafeBitCast. http://www.quora.com/Why-does-Swift-not-allow-implicit-type-conversion