Parse.com Access objects with 'includeKey' - swift

Good Day,
I use includeKey to fetch pointer objects, but I can use them... Here is my code:
var diagQuery = PFQuery(className: "CaseDiagnosis")
diagQuery.whereKey("patientcase",matchesQuery: caseQuery)
diagQuery.includeKey("patientcase")
var remoteDiags = diagQuery.findObjects()
println(remoteDiags)
console output:
[<CaseDiagnosis:IvQyy1i1ic:(null)> {
diagcode = "Z01.1";
firstcontact = "<FirstContact:7L3HB9Vnp2>";
patientcase = "<PatientCase:T2A4t37Iaw>";
}]
How do I access 'patientcase'?
My code so far:
for diag : PFObject! in remoteCases as [PFObject]{
// This does not require a network access.
var p = diag["patientcase"] as PFObject <----------Error
println("retrieved related post: \(p)")
}
I get an error:
fatal error: unexpectedly found nil while unwrapping an Optional value
What am I doing wrong?

From the sounds of the error, it might be complaining that one of the values in the remoteCases array is nil, try logging diag inside the loop.
Also be aware that if the PatientCase the pointer is pointing to has been deleted, you'll have issues also. The pointer will have the ID but the full object will be nil.

Related

Getting nil values when `map`-ing over array of entities

I'm using Core Data in an iOS app and executing the following Swift code which results in an error at the second line:
let movies = (try? container.newBackgroundContext().fetch(request)) ?? []
return movies.map { $0.name! } // error: unexpectedly found nil while unwrapping...
Note that in the example above it's 100% certain that there is no entity in movies with nil in name. The corresponding attribute in the Core Data model is set to not optional.
When I change the code as shown below (i.e. not inlining newBackgroundContext()) there is no error:
let context = container.newBackgroundContext()
let movies = (try? context.fetch(request)) ?? []
return movies.map { $0.name! } // no error this time
I'm quite new to Swift and assume it has something to do with memory management (e.g. context is deinited prematurely) but I would appreciate an actual explanation of why the error occurs in the first code listing.
Whenever you run map function on your array it returns an optional value. seems like there is no value in name and you are doing force unwrapping. try to use compactMap.
movies.compactMap { $0.name }

DynamoDB query returning nil every time even when the object exists

I have a query that returns nil each time I run it despite there being items with the key I pass.
I set my expression to the following:
queryExpression.keyConditionExpression = "#uID = :uidValue"
// in my model class
var uID: String?
uidValue is the value I'm comparing "uID" to.
I've read through AWS's documentation on this and haven't found anything that's helped.
//implementation of query
let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
dynamoDbObjectMapper.query(GameTracker.self, expression: queryExpression) { (output: AWSDynamoDBPaginatedOutput?, error: Error?) in
if(output == nil){
//create new user here, this keeps getting run each time
}else{
//user found, run other logic
}
}
I'm running uID's that I know exist in my table, but it keeps returning nil each time and throwing an error. Unfortunately, AWS docs on this don't offer many new insights into what might be going wrong from what I've found.
I resolved this by assigning uID as my partition key and just searching by hashkey instead.

Swift Issue with adding value to array for use within UITableView Controller

Confused as to why getting error "Cannot subscript a value of type 'inout [[String]]' (aka 'inout Array>'). Within a working table view class
(Originally followed Jared Davidson tutorial https://www.youtube.com/watch?v=pR6dR-vVZeY)
var secondArray = [SecondTable]()
let latest = ViewController().getArrayListLast()
var latestClass = latest.getFullClasses()
print(latestClass[0])
for i in 0...(latest.getAssetClasses().count)
{
if SecondTable(secondTitle: latestClass[i]) != nil
{
secondArray = secondArray.append(SecondTable(secondTitle: latestClass[i]))
}
}
append(_:) is mutating function and it doesn't return anything.
Now your code making 3 more mistakes.
As #vadian mentioned in comment ViewController() will never work when using storyboard.
It will give you run time crash index out of bounds because you have provide for loop till the array count but it should be till the less one of the array count, so it should like for i in 0..<(latest.getAssetClasses().count)
You are creating two times object with init of SecondTable to just check for the nil instead of that you can use if let.
if let secondTable = SecondTable(secondTitle: latestClass[i]) {
secondArray.append(secondTable)
}

Found nil for optional value?

I just can not figure this out :
print(module)
print(Globals.sharedInstance.dataModuleName)
let kind:NSString = module[Globals.sharedInstance.dataModuleName] as! NSString
Will print this, and then crash for a strange reason:
( //dic print
{
meta = no;
module = IN;
subject = LT;
variable = A2;
}
)
module // print the right field we are looking for inside the dictionary .
fatal error: unexpectedly found nil while unwrapping an Optional value
But you can see that module is a valid dictionary and also dataModuleName.
Crashing on the line let kind. What's wrong with it ?
Your module is Array of Dictionary not directly Dictionary, so you need to first access its first object then the module key like this
let kind:String = module[0][Globals.sharedInstance.dataModuleName] as! String
Note: One sugeestion, in swift use String instead of NSString
Also you can use if let and guard with initializtion to avoid crash.

Swift Error: Ambiguous reference to member 'subscript'

I'm new to coding and picked up some open source project to get the idea.
I'm getting the error:
Ambiguous reference to member 'subscript'
in the code below:
let pictures = ( selectedRestaurant["Pictures"] as! NSArray ) // Error
let picture = ( pictures[zoomedPhotoIndex] as! NSDictionary )
let pictureURL = picture["url"] as! String
let imageURL = NSURL(string: pictureURL)
let urlRequest = NSURLRequest(URL: imageURL!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) {
response, data, error in
if error == nil && data != nil {
self.imageView.image = UIImage(data: data!)
self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
}
}
Just specify explicitly what is the type of pictures:
So instead of:
let pictures = selectedRestaurant["Pictures"] as! NSArray
Write:
let pictures: NSArray = selectedRestaurant["Pictures"] as! NSArray
For me the answer was to specifically state the type of array I was casting to:
if let foo = dictionary["bar"] as? [String]
It means that "Pictures" is not a valid subscript. It looks like you are creating a constant named pictures and you are trying to assign it a value of selectedRestaraunt["Pictures"] and then trying to cast it as an NSArray. If selectedrestaraunt is already an array, then what goes in the [] brackets after selectedRestaraunt should be an integer value which will refer to an index in the selectedRestaraunt array. Obviosuly "Pictures" is not an integer, it is a string.
If you are trying to access an array within an array. Meaning that Pictures is an array stored within the selectedRestarauntarray then you can access it by using selectedRestaraunt[index of Pictures array] where [index of pictures array] is an integer which is equal to the index number in which the Picutres array resides within the selectedRestaraunt array
I managed to get this error in a somewhat weird way. I had code like this:
cell.textLabel = anArrayOfStrings[indexPath.item].uppercased()
And I was stumped as to why it couldn't figure out that this was an array, even though I very clearly declared its type. I broke the line in two and finally got a helpful error message:
let name = anArrayOfStrings[indexPath.item].uppercased()
cell.textLabel = name
I was trying to assign a String to a UILabel, but somehow the point at which the type inference engine failed was at the subscript.
So my advice to anyone stumped by this is to try to break up your statement into bite-sized chunks that the Swift type inference engine can more easily digest.
As Eric and Eugene mentioned in their comments it is impossible to review the issue you are having without knowing the selectedRestaurant type. That is after all why you are getting the compiler ambiguity error.
I have to respectfully disagree with MikeG though. The problem is not one of a valid subscript. You'd be getting that kind of error, if for example you had a selectedRestaurant type of [NSNumber:AnyObject], where clearly String is no longer valid since the dictionary key could only be an NSNumber.