Working with NSMutableArray in swift - ios

I have a NSMutableArray skippedArray of strings.
skipped Array = ["string1","string2","string3","string4"];
I want to assign the string at index 0 to an UILabel.
I tried lblQuestion.text = skippedArray[j] as! String
but the app crashes at this line.
Can anyone help?

Define NSMutableArray like this:
let skippedArray = ["string1","string2","string3","string4"];
lblQuestion.text = skippedArray.first
or you may also code like this:
let skippedArray : NSMutableArray = ["string1","string2","string3","string4"];
lblQuestion.text = skippedArray.firstObject as! String
There is another way to fetch object of NSMutableArray like this:
let skippedArray : NSMutableArray = ["string1","string2","string3","string4"];
let j = 0;
lblQuestion.text = skippedArray.object(at: j) as! String

Define your variable as Array or simply [String] or just let the definition define it as follows:
var skippedArray: Array<String> = ["string1","string2","string3","string4"]
or
var skippedArray: [String] = ["string1","string2","string3","string4"]
or
var skippedArray = ["string1","string2","string3","string4"]

First, define Mutable Array properly, as mentioned before
var skippedArray = ["string1","string2","string3","string4"]
Second, define your index, your called this "j"
let j = 0
Third, set label text with your string, from string array
lblQuestion.text = skippedArray[j]

Related

How to compare two arrays and remove matching elements from one array in Swift iOS

I have two arrays.
let array1 = ["Lahari", "Vijayasri"];
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"];
I want to remove the array1 elements in array2 and print the final array-like
result array = ["Ramya", "Keerthi"]
Converting the arrays to Sets and using subtract is a simple and efficient method:
let array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let resultArray = Array(Set(array2).subtracting(Set(array1)))
If maintaining the order of array2 is important then you can use filter with a set -
let compareSet = Set(array1)
let resultArray = array2.filter { !compareSet.contains($0) }
Paulw11 answer works perfectly. But if ordering in array is important you can do this:
let reuslt = array2.filter { !array1.contains($0) }
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.subtracting(otherSet))
}
}
var array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let a = array2.difference(from: array1) // ["Ramya", "Keerthi"]
Only take the end.
array2[array1.count...]

How to add String with double Quotes on start and end of the string in Array using swift

I want to make this type of result :
{"":[["someId","someName"]]}
I m trying to make like this :
var fields:[AnyObject] = [AnyObject]()
for someId:String in Preferences.getAllIds(){
let someName = Preferences.getAllNames(someId)
let value = String(format: "%#,%#", someId,someName)
var field:[String] = [String]()
field.append(value)
fields.append(field as AnyObject)
}
let dict = ["": fields]
Output i m getting is:
{"":[["012345,test_name"]]}
AS you can see : there are double duotes before 012345 and after test_name
"012345,test_name"
But I want to add at start and end on both sides of the strings.
Like : "012345","test_name"
I have tried to achieve required output by this trick but failed unfortunately (don't know why this doesn't work) ... :(
value1 = value.replacingOccurrences(of: ",", with: "\",\"")
you need to define it's array like this, Hope it will help you
var fields:[[String]] = [[String]]()
for someId:String in Preferences.getAllIds(){
let someName = Preferences.getAllNames(someId)
var arrValue : [String] = [String]()
arrValue.append(someId)
arrValue.append(someName)// ["someid","somename"]
fields.append(arrValue as [String]) // [["someid","somename"]]
}
let dict = ["": fields] // {"" : [["someid","somename"]]}
if you have static value Then you can make array like this
let arrValue : [String] = ["\(someId!)","\(someName!)"]

How to get the values from array with dicitionary in swift?

I want get the below json to my array for showing in UITableview
{
MyPets = (
{
breed = "";
breedvaccinationrecord = "";
"city_registration" = "";
"date_of_birth" = "";
"emergency_contacts" = "";
gender = m;
"pet_id" = 475;
"pet_name" = "IOS PET";
petinfo = "http://name/pet_images/";
"prop_name" = "";
"qr_tag" = 90909090;
species = Canine;
"vaccination_records" = "";
vaccinationrecord = "http://Name/vaccination_records/";
"vet_info" = "";
}
);
}
i am using below code to get values into array
if let dict = response.result.value {
print(response)
let petListArray = dict as! NSDictionary
self.petListArray = petListArray["MyPets"] as! [NSMutableArray]}
in cellForRowAtIndexPath i am using this line to display name in UILabel in TableCell
cell?.petName.text = self.petListArray[indexPath.row].valueForKey("pet_name") as? String
but it is crashing like
fatal error: NSArray element failed to match the Swift Array Element type
i am new to swift 2 please help me thanks in advance
First of all declare petListArray as Swift Array, do not use NSMutable... collection types in Swift at all.
By the way the naming ...ListArray is redundant, I recommend either petList or petArray or simply pets:
var pets = [[String:Any]]()
The root object is a dictionary and the value for key MyPets is an array, so cast
if let result = response.result.value as? [String:Any],
let myPets = result["MyPets"] as? [[String:Any]] {
self.pets = myPets
}
In cellForRow write
let pet = self.pets[indexPath.row]
cell?.petName.text = pet["pet_name"] as? String
It's highly recomenended to use a custom class or struct as model. That avoids a lot of type casting.

how to remove Duplicate values from Dict in swift 2.0

Hi I just want remove repeated objects should be removed in dictionary I am populating it in tableView
Here my sample code in 'CellForRowAtIndexPath'
controller.titleName = dict["itemName"] as? String
my output:
{
itemName = test;
},
{
itemName = funny;
},
{
itemName = vv;
},
{
itemName = hhh;
},
{
itemName = west;
}
First, i think thing you are using array to make dict so before load tableview/collectionview delete all replicated object from your array.
There is one option you have to create NSSet from NSArray so in NSSet all replicated object automatically removed . and then from NSSet you have to create NSArray.
convert set from array as follow
var set = NSSet(array: myarray)
To convert array for set
var newarry = set.allObjects as NSArray
Just try this
let uniqueArr = Array(Set(dict.values))
For your question I have tried separately and I got the answer
var arr = [AnyObject]()
var arrAppend = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let array = ["one", "one", "two", "two", "three", "three"]
let uniqueValue = Array(Set(array))
print("The unique value is - \(uniqueValue)")
let dictTest = ["itemName":"test"]
let dictFunny = ["itemName":"funny"]
let dictVVV = ["itemName":"vvv"]
let dictHHH = ["itemName":"hhh"]
let dictWest = ["itemName":"west"]
let dictTT = ["itemName":"tt"]
let dictWest1 = ["itemName":"west"]
arr.append(dictWest1)
arr.append(dictTest)
arr.append(dictVVV)
arr.append(dictTT)
arr.append(dictWest)
arr.append(dictFunny)
arr.append(dictHHH)
print("Array Response: \(arr)")
for keyValue in arr as Array
{
let getDictValueFromArray = keyValue["itemName"] as! String
arrAppend.append(getDictValueFromArray)
}
let unique = Array(Set(arrAppend))
print("the result is-\(unique)")
}
The Output for unique is
the result is-["funny", "test", "west", "vvv", "hhh", "tt"]

Crash while getting value from the dictionary in Swift

I have created a dictionary like
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
The application crashed when I tried to print all values from the dictionary like
let allValues = [Array](dictionary.values)
for value in allValues{
println(value)
}
I just started learning dictionary concept in swift language. I want to know my approach is right or wrong.
Please help me to figure it out
As Swift arrays have associated I don't think that you can declare type with array without specifying its associated type. I am not sure why you do not get compile time errors. This should work:
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array<AnyObject>] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
let allValues = [Array<AnyObject>](dictionary.values)
for value in allValues{
println(value)
}
Or even shorter:
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:[AnyObject]] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
let allValues = dictionary.values
for value in allValues{
println(value)
}
You can try this also
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
println("Array inside array \(tempArray2)")
var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
println(dictionary)
let allValues = Array(dictionary.values)
for value in allValues{
println(value)
}

Resources