Force casts should be avoided - ios

I am getting "Force cast violation : Force casts should be avoided warning"
on my code :
daysCombinedFinal = daysCombined[0] as! [Any?]
The screenshot is attached below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "location", for: indexPath) as? TravelShopCustomCell {
if !isFirstTime && self.nameArray.count != 0 {
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[0]]
daysCombinedFinal = daysCombined[0] as? [Any?] ?? []
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[0]]
startAMCombinedFinal = startAMCombined[0] as? [Any?] ?? []
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[0]]
endPMCombinedFinal = endPMCombined[0] as? [Any?] ?? []
cell.operatingDaysLabel.text = str
let isAMEqual = checkArrayStatus(testArray: [startAMCombinedFinal as Any])
let isPMEqual = checkArrayStatus(testArray: [endPMCombinedFinal as Any])
if isAMEqual && isPMEqual {
self.mergedArray = arrayMerger(array1: startAMCombinedFinal, array2: endPMCombinedFinal)
}
let startTimeString = self.mergedArray[0] as? String
let endTimeString = self.mergedArray[1] as? String
cell.operatingTimeLabel.text = startTimeString! + " - " + endTimeString!
return cell
} else if isFirstTime && self.nameArray.count != 0 {
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[indexPath.row]]
daysCombinedFinal = daysCombined[0] as! [Any?]
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[indexPath.row]]
startAMCombinedFinal = startAMCombined[0] as! [Any?]
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[indexPath.row]]
endPMCombinedFinal = endPMCombined[0] as! [Any?]
cell.operatingDaysLabel.text = str
let isAMEqual = checkArrayStatus(testArray: [startAMCombinedFinal as Any])
let isPMEqual = checkArrayStatus(testArray: [endPMCombinedFinal as Any])
if isAMEqual && isPMEqual {
self.mergedArray = arrayMerger(array1: startAMCombinedFinal, array2: endPMCombinedFinal)
}
let startTimeString = self.mergedArray[0] as? String
let endTimeString = self.mergedArray[1] as? String
cell.operatingTimeLabel.text = startTimeString! + " - " + endTimeString!
return cell
}
return cell
} else {
fatalError("Dequeueing SomeCell failed")
}
}
The array declaration is:
var dateArray = [Any]()
var endAmTimeArray = [Any]()
var endPmTimeArray = [Any]()
var startAmTimeArray = [Any]()
var startPmTimeArray = [Any]()
var combinedArray = [Any]()
var combinedStartAMArray = [Any]()
var combinedEndPMArray = [Any]()
var mergedArray = [Any?]()

Your problem has relation with concept of 'optional' & 'unwrapper'. Here is brief about both and difference between them: How to understand ! and ? in swift?
? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.
In your case, you are trying to get value from array using index number. Now type of elements of your array is 'Any'
So, there may be any kind of value/information contained by element of array. It will result into app crash, if you try to force unwrap a value of element, when it won't return a value or value with type that you're casting with unwrapper.
Here is basic tutorial in detail, by Apple Developer Committee.
This warning is indicating you, that your app may crash on force unwrapping optional value.
As a solution you should use ? (optional) with if-let block, to avoid force unwrapping and safe execution of your code, like:
if let daysC = daysCombined[0] as? [Any] {
daysCombinedFinal = daysC
}
Share your full source code, to get better solution of your query as you have not shared declaration of your array in your question. Because I've confusion about optional array [Any?] elements. Swift not allows array elements as optional.
Update : By considering elements of all arrays as 'Dictionary < String : Any >', forced unwraps from array assignments are removed here.
var daysCombined = [Any]()
var daysCombinedFinal = [Any?]()
daysCombined = [self.combinedArray[indexPath.row]]
// Update 1
// if combinedArray is an array of array
if let arrayElement = daysCombined[0] as? [Any] {
daysCombinedFinal = arrayElement
}
let str = daysCombinedFinal.flatMap { $0 as? String }.joined(separator:" ")
var startAMCombined = [Any]()
var startAMCombinedFinal = [Any?]()
startAMCombined = [self.combinedStartAMArray[indexPath.row]]
// Update 2
if let arrayElement = startAMCombined[0] as? [Any] {
startAMCombinedFinal = arrayElement
}
var endPMCombined = [Any]()
var endPMCombinedFinal = [Any?]()
endPMCombined = [self.combinedEndPMArray[indexPath.row]]
// Update 3
if let arrayElement = endPMCombined[0] as? [Any] {
endPMCombinedFinal = arrayElement
}
cell.operatingDaysLabel.text = str

Related

add the values according to appending the values

How to add the values according to appending the values in swift3.
this is my datasource:-
class QM_ChartDataSourceModel: NSObject {
var dataListArray:Array<QM_CartModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
newArray = self.getJsonDataStored22()
}
else{
newArray = array!
}
var datalist:Array<QM_CartModel> = []
for dict in newArray{
let model = QM_CartModel(dictionary: dict)
datalist.append(model!)
}
self.dataListArray = datalist
}
}
typealias dummyDataSource22 = QM_ChartDataSourceModel
extension dummyDataSource22{
func getJsonDataStored22() ->Array<Dictionary<String,String>>{
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]] as Array<Dictionary<String,String>>
return jsonArray
}
}
in tableviewcell:
func setEventData(carts:QM_CartModel)
{
self.name.text = carts.cartname
self.price.text = carts.cartsum
self.itemQuantityStepper.value = 1
setItemQuantity(quantity)
print(self.price.text)
let value = carts.cartsum
let x: Int? = Int(value!)
print(x)
let add = x!
print(add)
let theIntegerValue1 :Int = add
let theStringValue1 :String = String(theIntegerValue1)
self.price.text = theStringValue1
}
my model:-
class QM_CartModel: NSObject {
var cartname :String!
var cartprice:String!
var cartquantity:String!
var carttotalprice:String!
var carttotal:String!
var cartQR:String!
var cartvalue:String!
var cartsum:String?
var cartid:String!
init?(dictionary :JSONDictionary) {
guard let name = dictionary["name"] as? String else {
return
}
if let quantity = dictionary["quantity"] as? String{
let price = dictionary["price"] as? String
let id = dictionary["id"] as? String
self.cartid = id
self.cartprice = price
self.cartquantity = quantity
let fullNameArr = price?.components(separatedBy: " ")
let QR = fullNameArr?[0]
let value = fullNameArr?[1]
self.cartQR = QR
self.cartvalue = value
let x: Int? = Int(value!)
print(x)
let y:Int? = Int(quantity)
print(y)
let sum = x! * y!
print(sum)
let sum1 = String(describing: sum)
cartsum = sum1
}
my viewmodel:-
class QM_ChartViewModel: NSObject {
var datasourceModel:QM_ChartDataSourceModel
var insertedArray:QM_CartModel?
var filteredListArray:Array<QM_CartModel>? = []
var totalListArray:Array<QM_CartModel>? = []
init(withdatasource newDatasourceModel: QM_ChartDataSourceModel) {
datasourceModel = newDatasourceModel
print(datasourceModel.dataListArray)
}
func datafordisplay(atindex indexPath: IndexPath) -> QM_CartModel{
return datasourceModel.dataListArray![indexPath.row]
}
func numberOfRowsInSection(section:Int) -> Int {
return datasourceModel.dataListArray!.count
}
func delete(atIndex indexPath: IndexPath) {
datasourceModel.dataListArray!.remove(at: indexPath.row)
}
func search(idsearch :String?) {
filteredListArray = datasourceModel.dataListArray?.filter{($0.cartid?.range(of: idsearch!, options: .caseInsensitive) != nil)}
print(filteredListArray)
}
func searchindex(objectatindex index: Int) -> QM_CartModel {
return self.filteredListArray![index]
}
func total()
{ totalListArray = datasourceModel.dataListArray?.filter{($0.cartsum != nil)}
print(totalListArray)
}
func add(){
datasourceModel.dataListArray?.append(insertedArray!)
print(datasourceModel.dataListArray)
print(insertedArray?.offerAddName)
print(insertedArray?.offerprice)
self.datasourceModel.dataListArray = datasourceModel.dataListArray
print(insertedArray?.cartsum)
}
func addquantity(quantity:Int)
{
// datasourceModel.dataListArray?.filter{ $0.cartid! == cartaddedid! }.first?.qty = quantity as NSNumber?
}
}
in viewcontroller my code as below:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chartViewModel.numberOfRowsInSection(section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell: QM_ChartCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
if cell == nil {
tableView.register(UINib(nibName: "QM_ChartCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
}
cell.setEventData(carts: chartViewModel.datafordisplay(atindex: indexPath))
print(cell.numbers)
see here can see the total.So that way i need to display the total
this is my code ...here i getting the values model.cartsum.So this value is appending in var number:[String] = []
.But here i need-as values are appending ,here i need to add the number.So first value is 1 and second value is 2 then i need to add this values.And if next number is 3 then i need to get sum = 6.
How to get
You need to calculate all the cart stuff just after you get it either from service or from local. You don't need to do calculation in cellForRowAtIndex: method because it should be done once.
I assume this is your data structure as mentioned in question.
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],
["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],
["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],
["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],
["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],
["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],
["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],
["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],
["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],
["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]]
Here is how to calculate the total of the cart. As per your data considering price is in Int
var total = 0
for item in jsonArray {
/// Will check if quantity is available in dictionary and convertible into an Int else will be 0
let quantity = Int(item["quantity"] ?? "0") ?? 0
/// Will check price key exists in the dictionary
if let priceStr = item["price"] {
/// Will fetch the last components and check if it is convertible into an Int else 0
let price = Int(priceStr.components(separatedBy: " ").last ?? "0") ?? 0
/// Multiply price with quantity and add into total
total += price * quantity
}
}
print(total)
Output: 1776
Another way:
let total = jsonArray.map { (item) -> Int in
let quantity = Int(item["quantity"] ?? "0") ?? 0
let price = Int(item["price"]?.components(separatedBy: " ").last ?? "0") ?? 0
return quantity * price
}.reduce(0, +)
print(total)
Please try this code if you have array of Int
var arrayOfInt = [2,3,4,5,4,7,2]
let reducedNumberSum = arrayOfInt.reduce(0,+)
print(reducedNumberSum)
Answer: 27
In your code
let model = chartViewModel.datafordisplay(atindex: indexPath)
Please describe more so we can answer according your problem.

Swift4 : FMDBdatabase - Unexpectedly found nil while unwrapping an Optional value

Update:
In the end, I go to the local SQLite database and replace the NULL value to
"unkown". This works!
I am using FMDatabaseQueue to search an existing sqlite database in iOS.
//Data model
import Foundation
import UIKit
class scoreModel: NSObject {
var lessonName:String = String()
var lessonCode:String = String()
var creditPoint:Double = Double()
var totalStudentNumber:Int = Int()
var teacherName:String = String()
var semesterName:String = String()
var scoreValue:String = String()
var studentCount:Int = Int()
}
Unfortunately, there are some "" string in my database. Like:
teacherName ""
scoreValue ""
While searching, Xcode alerted that
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" in line "teacherName".
I don't need these "" results necessarily as they are not important. How can I fix it?
func queryDB(sql: String) -> NSMutableArray {
openDB ();
let resultArray = NSMutableArray()
SQLiteManager.shareInstance.dbQueue?.inDatabase { (db) in
let dbResult: FMResultSet! = db.executeQuery(sql, withArgumentsIn:[])
if (dbResult != nil)
{
while dbResult.next() {
let model:scoreModel = scoreModel()
model.lessonName = String(dbResult.string(forColumn: "lessonName")!)
model.lessonCode = String(dbResult.string(forColumn: "lessonCode")!)
model.creditPoint = Double(dbResult.double(forColumn: "creditPoint"))
model.semesterName = String(dbResult.string(forColumn: "semesterName")!)
model.teacherName = String(dbResult.string(forColumn: "teacherName")!)
model.totalStudentNumber = Int(dbResult.int(forColumn: "totalStudentNumber"))
model.scoreValue = String(dbResult.string(forColumn: "scoreValue")!)
model.studentCount = Int(dbResult.int(forColumn: "studentCount"))
resultArray.add(model)
}
}
}
return resultArray
}
Thank you!
The problem is that dbResult.string(forColumn: "teacherName") is returning an optional with a nil value, so maybe this object had a nil value when you saved it. It doesn't really matter, what's important is how you want to treat objects that don't have all the fields that you're expecting. The question you need to ask yourself is "how should I handle the case where the thing in the database doesn't have a teacher name?" Here are two ideas:
In order to be considered "valid," everything in the database needs to have all the properties I'm expecting, otherwise I ignore it. That would look like this:
while dbResult.next() {
if let lessonName = String(dbResult.string(forColumn: "lessonName")),
let lessonCode = String.dbResult.string(forColumn: "lessonCode")),
let creditPoint = Double(dbResult.double(forColumn: "creditPoint")),
let semesterName = String(dbResult.string(forColumn: "semesterName")),
let teacherName = String(dbResult.string(forColumn: "teacherName")),
let totalStudentNumber = Int(dbResult.int(forColumn: "totalStudentNumber")),
let scoreValue = String(dbResult.string(forColumn: "scoreValue")),
let studentCount = Int(dbResult.int(forColumn: "studentCount")) {
let model = scoreModel()
model.lessonName = lessonName
... // set lessonCode, etc
resultArray.add(model)
}
}
Another choice is to provide default values using optional coalescing or similar.
while dbResult.next() {
let lessonName = String(dbResult.string(forColumn: "lessonName")) ?? ""
let lessonCode = String.dbResult.string(forColumn: "lessonCode")) ?? ""
let creditPoint = Double(dbResult.double(forColumn: "creditPoint")) ?? ""
let semesterName = String(dbResult.string(forColumn: "semesterName")) ?? ""
let teacherName = String(dbResult.string(forColumn: "teacherName")) ?? ""
let totalStudentNumber = Int(dbResult.int(forColumn: "totalStudentNumber")) ?? 0
let scoreValue = String(dbResult.string(forColumn: "scoreValue")) ?? ""
let studentCount = Int(dbResult.int(forColumn: "studentCount")) ?? 0
let model = scoreModel()
model.lessonName = lessonName
... // set lessonCode, etc
resultArray.add(model)
}

Loop is taking too long to process

I am using following to code to arrange the array of contacts in sections (for e.g. contact with prefix "A" should show under "A" section). If there are contacts 4-5 hundred then it takes 20 sec to process.
Can you please check what is issue here? or any alternate for this.
let finalArr = NSMutableArray()
for contactDetail in conatctsArr {
let name = (contactDetail as! Dictionary)["givenName"] ?? ""// Getting First character of name
var key = String()
if name.characters.count > 0 {
let index1 = name.index((name.startIndex), offsetBy: 1)
key = name.substring(to: index1)
}
else {
key = ""
}
// getting all contatcts starting with particular character
let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %#",key)
let filteredArr = (conatctsArr as NSArray).filtered(using: predicate)
var dic = Dictionary<String, Any>()
dic["key"] = key
dic["values"] = filteredArr
if filteredArr.count > 0 && !(finalArr.contains(dic)) {
finalArr.add(dic)
}
}
Removing the filtered elements from the array after processing in each loop might improve the performance. Try:
let finalArr = NSMutableArray()
var processingArray = NSMutableArray(array:conatctsArr)
while processingArray.count > 0 {
let contactDetail = processingArray[0]
let name = (contactDetail as! Dictionary)["givenName"] ?? ""
var key = String()
if name.characters.count > 0 {
let index1 = name.index((name.startIndex), offsetBy: 1)
key = name.substring(to: index1)
}
else {
key = ""
}
let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %#",key)
let filteredArr = processingArray.filtered(using: predicate)
if filteredArr.count > 0 {
var dic = Dictionary<String, Any>()
dic["key"] = key
dic["values"] = filteredArr
finalArr.add(dic)
}
processingArray.removeObjects(in: filteredArr)
}
In your code, the filtering is being done multiple times for the same key. Try :
let finalArr = NSMutableArray()
for contactDetail in conatctsArr
{
let keysArray = [“A”, “B”, “C”,…. “Z”]
for key in keysArray
{
let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %#",key)
let filteredArr = (conatctsArr as NSArray).filtered(using: predicate)
var dic = Dictionary<String, Any>()
dic["key"] = key
dic["values"] = filteredArr
if filteredArr.count > 0) {
finalArr.add(dic)
}
}
}

How to iterate through Swift array and use data in iOS Chart?

I have a bar chart, which I am trying to populate through data pulled in from an array.
I am trying to iterate through this array in order to populate my chart.
Please note: in this example below there are 3 winningStreakDM variables hardcoded for testing purposes, but in 'real life' the number could be different each API call as it depends on how many 'users' are in that league.
This is why I need to iterate through the array and structure the data to suit.
let winningStreakDM1 : [String : Any] = [
"id" : 2,
"user_name" : "Dicky",
"winning_streak" : 5
]
let winningStreakDM2 : [String : Any] = [
"id" : 6,
"user_name" : "G",
"winning_streak" : 2
]
let winningStreakDM3 : [String : Any] = [
"id" : 5,
"user_name" : "Sultan",
"winning_streak" : 0
]
My issue is that I don't know how to iterate through the initial array to structure my data for it to work with the above code.
This is my full script:
import UIKit
import Charts
class CommunityLeagueStatsVC: UIViewController {
// GRAPHS *********
#IBOutlet weak var chartView: BarChartView!
var values = [BarChartDataEntry]()
// ****************
//********CHART VARIABLES**************//
//WINS LOSSES DRAWS
var winStreak: Double = 0.0
#IBOutlet weak var leagueStatsScrollView: UIScrollView!
var noDefeats: Bool?
var noWins: Bool?
var biggestWin: String?
var biggestWinTeams: String?
var passedCommunityName: String?
#IBOutlet weak var communityName: UILabel!
var playerId2: String?
var communityId2: String?
var eMail2: String?
override func viewDidLoad() {
super.viewDidLoad()
let winningStreak = ["Wins"]
let gamesWon = [winStreak]
setWinStreakChart(dataPoints: winningStreak, values: gamesWon)
let defaults = UserDefaults.standard
let Email = defaults.string(forKey: "userEmail")
let playerId = defaults.string(forKey: "playerId")
let commsId = defaults.string(forKey: "communityId")
self.playerId2 = playerId
self.communityId2 = commsId
self.eMail2 = Email
}
func setWinStreakChart(dataPoints: [String], values: [BarChartDataEntry]){
xAxis.valueFormatter = WinningStreakFormatter(chartView: self.chartView)
let barChartDataSet = BarChartDataSet(values: values, label: "Winning Streak")
barChartDataSet.colors = ChartColorTemplates.material()
let barChartData = BarChartData(dataSet: barChartDataSet)
barChartData.setValueFont(UIFont.systemFont(ofSize: 12.0))
self.chartView.data = barChartData
}
override func viewDidAppear(_ animated: Bool) {
let myUrl = URL(string: "http://www.xxx.uk/xxx/getLeagueStats.php")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "player_id=\(self.playerId2!)&community_id=\(communityId2!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["leagueStats"] as? [String:AnyObject] {
//WINNING STREAK
var values = [BarChartDataEntry]()
if let dataWinStreak = dict["winningStreak"] as? [[String : Any]] {
print ("test one")
for (index,item) in dataWinStreak.enumerated() {
if let yValue = item["winning_streak"] as? Int, let userName = item["user_name"] as? String {
print ("test two")
let barChartDataEntry = BarChartDataEntry(x: Double(index), y: Double(yValue), data: userName as AnyObject?)
values.append(barChartDataEntry)
}
}
self.setWinStreakChart(dataPoints: ["wins"], values: values)
}
catch{
print(error)
}
}
}
task.resume()
}
}
UPDATE:
These are the errors that I am currently receiving:
With a bit of playing around and commenting out the line containing the first error I have got to this stage which correctly shows a graph with values, but no xAxis containing the userNames of each player.
You can create array of BarChartDataEntry this way.
var values = [BarChartDataEntry]()
if let dataWinStreak = dict["winningStreak"] as? [[String : Any]] {
for (index,item) in dataWinStreak.enumerated() {
if let yValue = item["winning_streak"] as? Int, let userName = item["user_name"] as? String {
let barChartDataEntry = BarChartDataEntry(x: index, y: yValue, data: userName)
values.append(barChartDataEntry)
}
}
}
//Now use values array
Edit: You just need to change setWinStreakChart function because now you are working with dynamic data not static one.
func setWinStreakChart(dataPoints: [String], values: [BarChartDataEntry]){
let xAxis : XAxis = self.chartView.xAxis;
xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10.0)!
xAxis.labelTextColor = UIColor.black
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = true
xAxis.granularity = 1;
xAxis.labelPosition = .bottom
xAxis.valueFormatter = WinningStreakFormatter(chartView: self.chartView)
let barChartDataSet = BarChartDataSet(values: values, label: "Winning Streak")
barChartDataSet.colors = ChartColorTemplates.material()
let barChartData = BarChartData(dataSet: barChartDataSet)
barChartData.setValueFont(UIFont.systemFont(ofSize: 12.0))
self.chartView.data = barChartData
}
And now call this function after the for loop where we are creating array of BarChartDataEntry.
self.setWinStreakChart(dataPoints: ["wins"], values: values)

Cannot invoke append with an argument list of type json in IOS Swift

When I try to append a list which contain list of image which I parsed from JSON into an array in Swift iOS I mm getting an error:
"Cannot invoke append with an argument list of type json"
I'm totally new to iOS (Swift).
This is the basic code I'm using Alamofire, SwiftyJSON and SwiftyUserDefaults.
import Alamofire
import SwiftyJSON
import SwiftyUserDefaults
var NameArr: [String] = []
var ProfileImgArr: [String] = []
var StyleTypeArr: [String] = []
var ImageStackArr = [String]()
var SingleImageArr: [String] = []
var ItemNameArr: [String] = []
var TagsArr: [String] = []
var ImageArrSet: [String] = []
var LikeCountArr: [Int] = []
var ImageFlag: [String] = []
var testCount: (Int) = 0
var imageCounter = 0
var normalCounter = 0
var normalCounter1 = 0
var normalCounter2 = 0
// JSON load
let url = "http://zapmob.cloudapp.net/media/"
func JsonLoad() {
Alamofire.request(.GET, "http://zapmob.cloudapp.net/feed/?format=json")
.responseJSON { (request, response, data, error) in
println(error)
println(response)
let json = JSON(data!)
for (var j = 0; j <= json.count-1; j++) {
let FullName = json[j]["user_details_dict"]["username"].string
self.NameArr.append(FullName!)
let ProfilePic = json[j]["user_details_dict"]["profile_pic"].string
self.ProfileImgArr.append(ProfilePic!)
let StyleType = json[j]["fashion_type"].string
self.StyleTypeArr.append(StyleType!)
// -- Start of error part --v
var ImageStackArrs = [json[j]["images"].array!]
println(ImageStackArrs)
Defaults["ImageArrStack"] = ImageStackArrs
for (var x = 0; x <= ImageStackArrs.count - 1; x++) {
Defaults["ImageStackCache"] = [ImageStackArrs[x][0]]
}
// -- End of error part --^
let ItemName = json[j]["album_title"].string
self.ItemNameArr.append(ItemName!)
let LikeCount = json[j]["like"].count
self.LikeCountArr.append(LikeCount)
}
Defaults["NameCache"] = self.NameArr
Defaults["ProfileImgCache"] = self.ProfileImgArr
Defaults["StyleTypeCache"] = self.StyleTypeArr
Defaults["ItemNameCache"] = self.ItemNameArr
Defaults["TagsCache"] = self.TagsArr
Defaults["LikeCountCache"] = self.LikeCountArr
}
}
Without going through the code in detail: This error is normally called when trying to append to an optional array.

Resources