Pass data between 2 ViewControllers [duplicate] - ios

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 5 years ago.
I'm trying to send data from my first ViewController to my second One.
It works fine with a simple Int but with this Double it doesn't work and I don't understand why. So if you can explain why it doesn't work it's cool !
My declaration in first ViewController :
var time: Double? = 0.00
Then I try to send it to my other ViewController:
let vc = segue.destination as! MySecondViewController
vc.rows = rows[pathForAVC]
vc.lap = lap[pathForAVC]
vc.indexPath = pathForAVC
vc.time = rows[pathForAVC]["Time"]! as! Double
fatal error: unexpectedly found nil while unwrapping an Optional value
And my second ViewController:
var time: Double? = 0.00
topLabel.text = "\(time!)"
N.B:
rows is a Dictionnary:
var rows: [[String : AnyObject]] = [[:]]
I really don't understand my mistake...

The problem is that you are force unwrapping a value that may not be there:
vc.time = rows[pathForAVC]["Time"]! as! Double
If rows[pathForAVC]["Time"]! is nil, your application will crash. You should really avoid using ! unless your application simply cannot continue operating without that value. And those situations should be rare.
You should instead safely unwrap your value using an if let statement like this:
if let unwrappedTime = rows[pathForAVC]["Time"] as? Double {
print(unwrappedTime)
}
(I'm not near Xcode right now but the above code should be close enough to get valuable hints from the compiler).
Let me know if you need any more clarification.

Related

Why are my variable or cast empty in my iOS app? [duplicate]

This question already has an answer here:
Why are my variables empty when I cast them in my iOS application?
(1 answer)
Closed 1 year ago.
I'm coding an app on Xcode for IOS and I'd like to send a variable to another ViewController that hasn't appeared yet. The problem is that when I make a variable of my future ViewController like this :
guard let EndConfiguration = self.storyboard?.instantiateViewController(withIdentifier: EndConfiguration) as? EndConfiguration else
{
fatalError("Impossible d'acceder correctement au cellules des alarmes")
}
And I'm trying to do this:
EndConfiguration.ModeleOutlet.text = Alarme.shared.Alarmes[indexPath.row].Modele
I get this error :
Fatal error: Unexpectedly found nil while implicitly unwrapping an
Optional value
I understood the Optionels but if I add a "?" after ModeleOutlet it will remove the error but the text remains unchanged in my other ViewController. I'm sure that the value I modify is full, don't worry.
I'm replicating my problem because someone close it because there was already a solution when there wasn't one at all.
Thank you in advance.
try this
guard let EndConfiguration = self.storyboard?.instantiateViewController(withIdentifier: EndConfiguration) as? EndConfiguration else
{
fatalError("Impossible d'acceder correctement au cellules des alarmes")
}
_ = EndConfiguration.view
EndConfiguration.ModeleOutlet.text = Alarme.shared.Alarmes[indexPath.row].Modele
I am making the assumption that type of ModeleOutlet is a Label or of another type that may contain a text variable.
If ModeleOutlet is indeed a label that is attached via storyboard, then I urge you to read up on the ViewController lifecycle. Here is a great article describing it : https://medium.com/good-morning-swift/ios-view-controller-life-cycle-2a0f02e74ff5
Now, to answer your question specifically, you'll likely want to create a separate variable within your view controller then set the text variable within the function, viewDidLoad.
class EndConfiguration: UIViewController {
public var sharedText: String?
#IBOutlet var ModeleOutlet: UILabel?
func viewDidLoad() {
super.viewDidLoad()
self.ModeleOutlet?.text = sharedText
}
}

What is difference between below 2 lines? [duplicate]

This question already has answers here:
What's the difference between "as?", "as!", and "as"?
(3 answers)
Closed 4 years ago.
I am trying to add code in cellForRowAt indexPath method like below
cell.itemNameLabel.text = nameArray[indexPath.row]
but it is showing error as Cannot assign value of type 'Any' to type 'String?'
so it can be solved by below 2 ways,
cell.fruitName.text = fruitArray[indexPath.row] as? String
or
cell.fruitName.text = (fruitArray[indexPath.row] as! String)
so, my question is what is the difference between 2 answers?
cell.fruitName.text = fruitArray[indexPath.row] as? String
Above return type is optional value. means it will be nil value return if array is not consist string value.
cell.fruitName.text = (fruitArray[indexPath.row] as! String)
Above return type is non-optional value. means it will be fire fatal error if array is not consist string value.
Below is the generic information for all optionals. Please find it.
When you are using ! and the fruitArray[indexPath.row] is nil it will trigger run time error but if use ? it will fail gracefully.
You can find more detail information in Apple document

fatal error: unexpectedly found nil , I define a gesture, this method is the method of gesture binding [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
//fatal error: unexpectedly found nil while unwrapping an Optional value
let translationInContainerView = gesture.translation(in: transitionContainerView!)
Occasionally crash,not every time.
I want to catch this exception,in the case of such a situation(found nil),don't want the program to crash,who can tell me how to solve this problem.
I try this,but no use:
Try this:
guard let transitionContainerView = self.transitionContext?.containerView else {
print("the containerView of transitionContext is nil. Find out why.")
return
}
You might need to cast the transitionContainerView object with a specific type. I don't know what the type is supposed to be but it would look something like this:
guard let transitionContainerView = self.transitionContext?.containerView as? MyValueType else {
print("the containerView of transitionContext is nil. Find out why.")
return
}
The addition here is the as? MyValueType portion
If you don't hit the code block within the else statement, then it is not nil and you should be able to use your object accordingly. I hope this helps!

How to use optional "?" and "!" in swift? [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I am studying XCode7.3. The "?" and "!" always make me confused.
I have code like below.
The lines name : name, type : type and image : image displaying error message :
Value of optional type 'String?' not unwrapped, did you mean to use '!' or '?'?
#IBAction func unwindToHomeScreen( segue : UIStoryboardSegue ) {
if let addRestaurantController = segue.sourceViewController as? AddRestaurantController {
let name = addRestaurantController.name
let location = addRestaurantController.location
let type = addRestaurantController.type
let isVisited = addRestaurantController.isVisited
let image = addRestaurantController.imageView
restaurants.append( Restaurant(
name : name,
type : type,
location : location,
phoneNumber : "UNKNOW",
image : image,
isVisited : isVisited? ?? false
) )
print( addRestaurantController.imageView )
}
}
I modify code to name : name! or name : name?, it still doesn't work. How can I fix it?
I think this will solve your problem.
If addRestaurantController.location, addRestaurantController.name and addRestaurantController.type are optional.
#IBAction func unwindToHomeScreen( segue : UIStoryboardSegue ) {
if let addRestaurantController = segue.sourceViewController as? AddRestaurantController , name = addRestaurantController.name, location = addRestaurantController.location, type = addRestaurantController.type, isVisited = addRestaurantController.isVisited, image = addRestaurantController.imageView
{
restaurants.append( Restaurant(
name : name,
type : type,
location : location,
phoneNumber : "UNKNOW",
image : image,
isVisited : isVisited? ?? false
) )
}
}
You haven't specify that whether addRestaurantController.location, addRestaurantController.name and addRestaurantController.type are optional or not. And you randomly submitted your question without even analysing it properly.
Please give more value to other people's time. And ask meaningful questions. Read more about guidelines for a Stackoverflow question.
There might be few reasons, but first I'd suggest you to read about optionals (?) and explicitly unwrapped optionals (!) here https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
As far as the problem, it is most likely that optionality of variable name in Restaurant is defined differently comparing to local definition. While locally variable name is defined to be optional, e.g. let name: String?, Restaurant expects it to be non optional (probably it defined as let name: String (note no ? at the end)). That mean that you need to unwrap optional value to pass it to the Restaurant (please see the link above for ways of unwrapping, there are few depending on your use-case)
If you are switching to Swift 3, keep in mind that behavior of explicitly unwrapped optionals changed. For motivation and in depth description, please read this proposal https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md
But as it's been pointed out, Swift 3 can not be compiled in Xcode 7, you need to download beta of Xcode 8 for that

fatal error: unexpectedly found nil while unwrapping an Optional value(When adding to a array)

I have some code that receives value from a segue and replaces a certain element of an array with the index number that I have.
The initialization of the variables is:
var noteTitles: [String] = ["Sample Note"]
var noteBodies: [String] = ["This is what lies within"]
var selectedNoteIndex: Int!
var newTitle: String!
var newBody: String!
and I have a segue that makes the last 3 values the values that I want them to be.
under viewDidLoad(), I have this:
if newTitle == nil && newBody == nil {
}
else {
println("\(newTitle)")
println("\(newBody)")
println("\(selectedNoteIndex)")
let realTitle: String = newTitle
let realBody: String = newBody
let realIndex: Int = selectedNoteIndex
noteTitles[realIndex] = realTitle
noteBodies[realIndex] = realBody
}
My logs show this:
New Note Title
This is what lies within
nil
fatal error: unexpectedly found nil while unwrapping an Optional value
and I get
Thread 1: EXC_BAD_INSTRUCTION(code=EXC_i385_INVOP,subcode=0x0)
on the line
let realIndex: Int = selectedNoteIndex
Can anyone tell me what I'm doing wrong?
var varName: Type! declares an implicitly unwrapped optional.
It means that it will be automatically unwrapped when accessing the value with varName, i.e. without using varName!.
Thus, accessing the implicitly unwrapped optional selectedNoteIndex with let realIndex: Int = selectedNoteIndex when its value is actually nil results in the error you got.
Apple's Swift Guide states that:
Implicitly unwrapped optionals should not be used when there is a
possibility of a variable becoming nil at a later point. Always use a
normal optional type if you need to check for a nil value during the
lifetime of a variable.
The reason I was getting these errors is because while segueing back to the main view, I was not using the proper unwind segue, and instead using another show segue, which erased all data that had previously been within the view controller. By creating a unwind segue, I was able to keep the values before the segue to the detail view and prevent the error.
Because you did not assign value for selectedNoteIndex so it shows nil. First, you have to check whether its not nil value.
if let selectedNoteIndex = realIndex{
let realIndex: Int = selectedNoteIndex
}

Resources