Swift ! does not remove Optional() - swift

Before, I have successfully added a ! to force an unwrap to remove the "Optional()" from a variable. I am unable to do this in data returned from Parse.com
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
println(object[myObject]!)
}
} else {
println("Error: \(error) \(error.userInfo!)")
}
}
In the example above, the entire table from the Parse.com class is returned and printed to the console. However,
Optional(...)
is returned for each line even though I force an unwrap using ! at the end
What am I missing?
(Note: myObject is the name of the Column in the Parse Class database)

MirekE was right. It was a nested Optional(Optional()).
to fix I:
println(object[myObject]!!)

You only have to put "!" at the end of your variable, in print area
self.addressLabel.text = "\(subThoroughfare) \(p.thoroughfare!) \n \(p.subLocality!) \n \(p.subAdministrativeArea!) \n)".

Related

Confused on Error Handling in Swift 3

I got confused error handling in swift3. I try to do like "if XX function got error then try YY function"
Let me show you what I try:
class MyClass {
enum error: Error
{
case nilString
}
func findURL() {
do {
let opt = try HTTP.GET(url_adr!)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
do
{
/* This is func1. and got error. I want to if this function has error then go next function. */
try self.stringOperation(data: response.description)
}
catch{
print("doesn't work on func1. trying 2nd func")
self.stringOperation2(data:response.descritption)
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
func stringOperation(data:String)throws -> Bool{
do{
/** 1 **/
if let _:String = try! data.substring(from: data.index(of: "var sources2")!){
print("its done")
}else{
throw error.nilString
}
IN 1: I got this fatal error on this line:
"fatal error: unexpectedly found nil while unwrapping an Optional value" and program crashed.
I googled error handling try to understand and apply to in my code. However not succeed yet. Can someone explain where did I wrong?
Additional info: I got String extension for .substring(from:...) , and .index(of:"str"). So these lines doesn't got you confused.
As a general rule, try avoiding using force unwrapping (!), where you have
if let _: String= try! data.substring...
Instead use
if let index = data.index(of: "var sources2"),
let _: String = try? data.substring(from: index) { ... } else { ... }
That way you remove the two force unwraps that may be causing your crash. You already have the if let protection for catching the nil value, so you can make the most of it by using the conditional unwrapping.

query if the data is found - Parse & Swift 3

I'm trying to develop an app that provide User sign up and within the UI I want to query if the email is exists or not.
The problem is since I change from swift 2 to swift 3 I got these errors
var query = PFObject(className:"User")
query.whereKey("email", equalTo: email)
query.findObjectsInBackground {
(objects, error) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {
print(object.objectId)
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
/Users/**************/SignUpSenderViewController.swift:49:9:
Value of type 'PFObject' has no member 'whereKey'
/Users/i*************/SignUpSenderViewController.swift:50:9:
Value of type 'PFObject' has no member 'findObjectsInBackground'
any suggestion to solve this challenge ?
I dont know what documentation you checked but the query has to be done this way...
let query = PFQuery(className:"_User")

Array of Parse Pointers (Swift) - is This Possible

I am working on an app where the user is connected (in) multiple school classes. Since a student will be in more than one class, am I able to set an array of pointers to an individual user or is that not possible (maybe a relation is better)?
Here is my code:
let classPointerQuery = PFQuery(className: "Classes")
classPointerQuery.whereKey("class_name", equalTo: self.classNameTextField.text!)
let classQuery = PFQuery.orQueryWithSubqueries([classPointerQuery])
classQuery.findObjectsInBackgroundWithBlock({ (results: [PFObject]?, error: NSError?) -> Void in
if let objects = results {
for object in objects {
let userInfo = PFUser.currentUser()!
userInfo["my_classes"] = object
userInfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error != nil {
spinningActivity.hideAnimated(true)
self.displayAlert("Error", message: error!.localizedDescription)
} else if success {
spinningActivity.hideAnimated(true)
self.dismissViewControllerAnimated(true, completion: nil)
} else {
spinningActivity.hideAnimated(true)
self.displayAlert("Something Went Wrong", message: "Please try again")
}
})
}
}
})
* Note: I also tried changing - userInfo["my_classes"] = object - to - userInfo["my_classes"] = [object] - and got an error, "invalid type for key my_classes, expected *Classes, but got array (Code: 111, Version: 1.12.0)"
What I am doing here is querying for the object of the class that I want - lets say the user wants to add the class "Physics" - the query queries for the "class_name" in the Parse class "Classes" and spits out the object. This object is then set the current user's "my_classes" -> a pointer object. I there a way, when the user wants to add "Calculus" that the pointer object in Parse will have 2 pointers instead of replacing the current pointer?
Thanks in advance for the help!
you cant store Pointers in array, you can store objectID in the array as string and do the query like that.... the general rule is that u use Pointers for 1:many relationships in database and Relations in many:many...
Update 1 - Saving objectID to Array in Parse
PFUser.currentUser()!.addObject(somePFObject.objectID!, forKey: "my_classes")
for queries you will than use containedIn
querySetup.whereKey("class", containedIn: array)

Cannot assign result of Parse PFQuery to instance variable of my controller Class in Swift

I'm trying to assign the value returned from the result of a Parse query to an instance variable of my view controller class called "currentProfile". Although the function retrieves the data from the server okay, it seems like it doesn't assign it to my instance variable.
This is my code :
let query = PFUser.query()
query!.getObjectInBackgroundWithId(self.profileId) {
(profile: PFObject?, error: NSError?) -> Void in
if error == nil && profile != nil {
print(profile)
self.currentProfile = (profile as? PFUser)!
} else {
print(error)
}
}
print(currentProfile)
So when I print profile the first time it prints it correctly, however when I print currentProfile outside the function it actually doesn't print anything.
If you have any idea why this is happening or know how could I fix it, it would be greatly appreciated if you could let me know.
Thanks.

pointers in parse class with swift code

I'm trying to insert a text under description column, and it keep giving me error, I think I'm having this issue because I wasn't able to use the pointer properly.. is there any one can help, I watched a number of tutorial video's as to how to setup the pointer in Parse, and that didn't solve the issue.
Thanks.
let me = self.textField.text
let query = PFQuery(className: "Store")
query.getObjectInBackgroundWithId ("product", block: {
(object: PFObject?, error: NSError?) -> Void in
if error != nil
{
print(error)
}
else if let transaction = object {
transaction["discription"] = "\(me)"
transaction.saveInBackground()
print(object!.objectForKey("discription"))
}
})
I finally got the answer, the best possible answer I got was, not store any information to the DB till all the input is done from the last page. It means you carry over the input as temp to each pages, then save it at the end... :)