Swift 4 error with appending data into an array [duplicate] - swift

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
In my app I have a group of arrays that I append with data from an API. The method is as follows:
let noOfCountries = APIData.data.count
while self.countries < noOfCountries{
self.idArray.append(APIData.data[self.countries].id!)
self.countryIntroArray.append(APIData.data[self.countries].countryIntroTab!)
self.countryNameArray.append(APIData.data[self.countries].countryName!)
self.flagArray.append(APIData.data[self.countries].countryFlag!)
self.countryEventsArray.append(APIData.data[self.countries].countryEventsTab!)// App crashes here with this error: Unexpectedly found nil while unwrapping an Optional value
self.countries += 1
}
For some reason the app crashes at at self.countryEventsArray.append. The arrays are declared as follows:
var idArray = [Int]()
var countryIntroArray = [String]()
var countryNameArray = [String]()
var flagArray = [String]()
var countryEventsArray = [String]()
The structs are set as such:
let id: Int?
let countryName: String?
let countryFlag: String?
let countryIntroTab: String?
let countryEventsTab: String?
What is it that I'm doing wrong? If I remove the exclamation from self.countryEventsArray the app will not run at all.

you shouldn't append api data into array without any data exist check
use the same code for check
if let myData = APIData.data[self.countries].countryEventsTab {
self.countryEventsArray.append(myData)
}

Related

Dictionary<string,Dictionary> in swift 3.0 giving nil when tried to add a dict [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.
var dist: Dictionary<String, NSObject>!
var bigDist : Dictionary<String, Dictionary<String, NSObject>>!
self.bigDist["1" as String] = self.dist
When I try to do this, I get an error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Data set for self.dist:
Optional(["hits": 0, "name": India lags behind China in consumer spends: Stefano Ricci’s Jackie Manglani, "web": Livemint, "id": -1655, "like": 0, "iurl": http://www.livemint.com/rf/Image-222x148/LiveMint/Period2/2017/02/21/Photos/Processed/jackiemanglani2-kXhC--621x414#LiveMint.JPG, "notify": 0, "date": 201655200217, "active": 1, "type": Mark, "dateAdded": 20/02/2017, "url": http://www.livemint.com/Consumer/3NT8Vbw7BcGeoPJNMoyK5H/India-lags-behind-China-in-consumer-spends-Stefano-Riccis.html])
Your variable bigDist is an implicitly unwrapped optional. (You declare it with) your_type!.
That means that:
It can contain a nil.
You don't need to unwrap it using ? or !.
If you reference it and it contains nil, you'll crash.
Number 3 is what's happening.
You need to create an empty dictionary. Try getting rid of the ! in the declaration, and creating an empty dictionary when you declare it:
var bigDist : Dictionary<String, Dictionary<String, NSObject>> = [:]
You did not initialize bigDist:
var dist: Dictionary<String, NSObject>? = nil
var bigDist = Dictionary<String, Dictionary<String, NSObject>>()
self.bigDist["1"] = self.dist
The code could be swiftier anyway. Using [String: NSObject] instead of Dictionary<String, NSObject> (which is exactly the same) makes the code easier to read and can prevent such a mistake like you did.
var dist: [String: NSObject]? = nil
var bigDist = [String: [String: NSObject]]()
self.bigDist["1"] = self.dist

Dynamic Struct creation in Swift - based on user input

I am trying to create dynamic struct in swift based on user input.
struct Diagnosis {
var diagName = String() // Name of the diagnosis
var diagSymptoms = [String]() // Symptoms of the diagnosis in a ranked array to identify prevelancy
var diagSpecialization = [String]() // the specializations which would mostly encounter this diagnosis
var diagRank = Int() // the overall rank of the diagnosis
var diagSynonoms = [String]() // the other name thru which the same diagnosis is called / referred.
// func init(diagName: String(),diagSymptoms: [String](),diagSpecialization: [String](),diagSynonoms: [String]())
init( let pasdiagName: String,let pasdiagSymptoms:Array<String>) {
self.diagName = pasdiagName
self.diagSymptoms = pasdiagSymptoms
}
}
var maleria = Diagnosis(pasdiagName: "Maleria",pasdiagSymptoms: ["fever","chill","body pain"])
The above creates the structure maleria - But in future I want to have the input from user and create a structure for that inputted string
var abc = "typhoid"
let valueof(abc) = Diagnosis()
The value of function is something I just put here arbitrarily to make my explanation clear.
I know I could do this in python and I am new to swift. Thanks in advance for the help.
As #Wain suggested, you should use a Dictionary.
This is how you create a mutable dictionary where the key is a String and the value can be any type.
var dict = [String:Any]()
This is how you put key/value pairs into the dictionary
dict["year"] = 2016
dict["word"] = "hello"
dict["words"] = ["hello", "world"]
And this is how you extract a value and use it
if let word = dict["word"] as? String {
print(word) // prints "hello"
}

Swift 2.0: Type of Expression is ambiguous without more context? SortInPlace

This error occured in SWIFT 2.0. There are a lot of similar error messages, but I couldn't match them to my code:
class fileObj : Comparable {
var URL = NSURL()
var path = String()
var filename = String()
var fileExtension = String()
...
}
...
var images = [fileObj]() // array of all files (images)
images.sortInPlace( { $0.URL.absoluteString! > $1.URL.absoluteString! } ) // sort by name
The last row causes the error message, indicating, that $0 is wrong. Any idea?
NSURL's absoluteString is non-optional and you're force unwrapping it.
Rewrite the sort as follows
images.sortInPlace( { $0.URL.absoluteString > $1.URL.absoluteString } )

What does StringInterpolationSegment do? (swift)

I continued on my math question project, and it could now generate questions, so I need to try to use a global variable to use my answer's in generating the answer itself and putting the answer randomly into one of 4 choices. I decided to put a secret label outside of my view that shows the answer. Here's my code:
//important stuff
#IBOutlet var secretAnsarrrrr: UILabel!
//useless code
//declare the value of secretAnsarrrr
secretAnsarrrrr.text = String(answer)
numA.text = String(Int(randomNumber))
numB.text = String(Int(randomNumber2))
}
generateQuestion()
}
var optionAnswer:UInt32 = arc4random_uniform(4)
#IBAction func answerA(sender: UIButton) {
var otherAns:String = String(secretAnsarrrrr) //error
if optionAnswer == 0 {
optionA.text = secretAnsarrrrr.text
}
Doing so gives me the error of 'Missing argument label: StringInterpolationSegment in call'. It tells me to place it behind 'secretAnsarrrrr' in the parentheses. What does stringInterpolationSegment do and how do I fix this?
secretAnsarrrrr is not a string itself - it is a UILabel which also contains information like color and font. You need to tell Swift to use its text property:
var otherAns:String = String(secretAnsarrrrr.text)
I just encountered this error, and after some head scratching, I realised that I needed to unwrap an optional integer which I was trying to parse with String(...). As soon as I added the exclamation mark, the problem was solved:
var num: Int? = 1
var str = String(num!)
it is Better to write:
var num: Int? = 1
var str = num.map { String($0) } // if num == nil then str = nil else str = string representation

Swift Convert comma separated string to NSMutableArray [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 7 years ago.
I have the following string
var points = "4,5"
I would like to convert to a mutable array so it becomes [4,5]
I tried the following but it did not work
var points = "4,5"
var selectedArray : NSMutableArray = [points]
Swift 2:
Here you go:
var points = "4,5"
var pointsArr = split(points) {$0 == ","}
or
var pointsArr = points.componentsSeparatedByString(",")
Source: Swift: Split a String into an array
Swift 3:
as gomfucius mentioned:
var arr = points.components(separatedBy: ",")