Find an item and change value in custom object array - Swift - ios

I have this class
class InboxInterests {
var title = ""
var eventID = 0
var count = ""
var added = 0
init(title : String, eventID : NSInteger, count: String, added : NSInteger) {
self.title = title
self.eventID = eventID
self.count = count
self.added = added
}
}
And i use it like this
var array: [InboxInterests] = [InboxInterests]()
Add item
let post = InboxInterests(title: "test",eventID : 1, count: "test", added: 0)
self.array.append(post)
I want to find the index by eventID key and change the value of added key in the same index
How is that possible?

For me, the above answer did not work. So, what I did was first find the index of the object that I want to replace then using the index replace it with the new value
if let row = self.upcoming.index(where: {$0.eventID == id}) {
array[row] = newValue
}
In Swift 5.0:
if let row = self.upcoming.firstIndex(where: {$0.eventID == id}) {
array[row] = newValue
}

Since you are using a class, use filter and first to find the value:
array.filter({$0.eventID == id}).first?.added = value
In this you:
filter the array down to elements that match the event ID
pick the first result, if any
then set the value
This works since classes are pass by reference. When you edit the return value from array.filter({$0.eventID == id}).first?, you edit the underlying value. You'll need to see the answers below if you are using a struct
EDIT: In Swift 3 you can save yourself a couple of characters
array.first({$0.eventID == id})?.added = value
EDIT: Swift 4.2:
array.first(where: { $0.eventID == id })?.added = value
array.filter {$0.eventID == id}.first?.added = value

The filter operator is not the best in this case, it works for some of you because classes are passed by reference.
Explanation: (You can copy the following code in a playground if you want to verify it).
class Book {
let id: Int
var title = "default"
init (id: Int) {
self.id = id
}
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
print(book.title)
}
arrayBook.filter{ $0.id == 1 }.first?.title = "modified"
arrayBook.forEach { book in
print(book.title)
}
Arrays are copied by value not reference, so when you are using filter you are creating a new array (different than the initial), but when you modify the new one, the initial one gets modified too because both are pointing to the same class (classed are passed by reference), so after the filter your array will have changed and the new one gets deallocated. So in this case it will print "default", "default" and then "default, "modified".
What happens if you change class for struct, the value will be passed by value not reference so you will have 2 arrays in memory with different values, so if you go through arrayBooks again it will print before the filter "default","default", and then "default", "default" again. Because when you are using the filter you are creating and modifying a new array that will get deallocated if you do not store it).
The solution is using map, creating a new array with all the values but with the modified items or fields that we want and then replace our array with the new one. This will print "default", "default" before the map, and then "default", "modified"
This will work with structs, classes and everything that you want :).
struct Book {
let id: Int
var title = "default"
init (id: Int) {
self.id = id
}
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
print(book.title)
}
arrayBook = arrayBook.map{
var mutableBook = $0
if $0.id == 1 {
mutableBook.title = "modified"
}
return mutableBook
}
arrayBook.forEach { book in
print(book.title)
}

array = array.map { $0.eventID == id ? newValue : $0 }

If you conform your class to Equatable then this would work:
extension Array where Element: Equatable {
#discardableResult
public mutating func replace(_ element: Element, with new: Element) -> Bool {
if let f = self.firstIndex(where: { $0 == element}) {
self[f] = new
return true
}
return false
}
}
Use like this:
array.replace(prev, with: new)

Related

Access Value in Dictionary using Random Number

I am trying to access the value from a dictionary using a random number, but I am lost, can someone please guide?
Here is what I have:
var themes = ["Halloween": "πŸ˜ˆπŸ’€πŸ€‘πŸ‘»πŸ€–πŸ‘½", "Sports": "πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±" , "Faces": "πŸ˜€πŸ˜πŸ˜¨πŸ€—πŸ˜€πŸ€€", "Animal": "πŸ¦“πŸ˜ΌπŸ˜ΊπŸ˜ΏπŸ™€πŸ™ˆ"]
// This Does not work for some reason?
lazy var themeRandomNumber = themes.count.arc4random
lazy var currentTheme = themes[themeRandomNumber]
//Cannot subscript a value of type[String : String]' with an index of type 'Int'
This makes sense since, I am trying to access the key using an Int when it is obviously a String, but not sure how to proceed?
lazy var currentEmoji = themes[currentTheme]
extension Int{
var arc4random: Int{
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return -Int(arc4random_uniform(UInt32(abs(self))))
} else {
return 0
}
}
}
Just replace
lazy var currentEmoji = themes[currentTheme]
with
var currentTheme = themes.randomElement()
print(currentTheme?.value) //Optional("πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±")
print(currentTheme?.key) //Optional("Sports")
Here randomElement is new property which you can use to get random element.
Because you're not accessing the key of your dictionary, you need to select "Halloween", "Sports", "Faces" or "Animal" - your themes dict's keys.
You can use some custom mapping method with Int.random(in: 0...3) or a Keys enum conforming to CaseIterable, and then you need to select a random character (emoji) in the String for your given Key (via a random number in the range 0..<string.length).
EDIT
With Swift 4.2+ (Xcode 10) you can use randomElement():
var themes = ["Halloween": "πŸ˜ˆπŸ’€πŸ€‘πŸ‘»πŸ€–πŸ‘½", "Sports": "πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±" , "Faces": "πŸ˜€πŸ˜πŸ˜¨πŸ€—πŸ˜€πŸ€€", "Animal": "πŸ¦“πŸ˜ΌπŸ˜ΊπŸ˜ΏπŸ™€πŸ™ˆ"]
var randomEmoji = themes.randomElement()?.value.randomElement()

How to reduce an array in swift based on some condition

I need to know a good solution in Swift for the below problem I am facing.
I have an array of models declared as var dataArray = [PlanModel]().
class PlanModel: {
var isPurchased:String?
var planName:String?
}
Now I get data from the server and I fill the dataArray with the models. The dataArray consists of 3 models. The value of models are:
Model 1:
isPurchased = "true"
planName = "Question"
Model 2:
isPurchased = "true"
planName = "Personal"
Model 3:
isPurchased = "false"
planName = "Full"
What I need is to reduce this array by checking if the plan is purchased by checking value of isPurchased. If it's true remove it from array, if its false, then keep that in the array.
Please tell me what would be the simpler and efficient way of doing this in Swift?
You can use the filter function
var reducedArray = dataArray.filter {$0.isPurchased == "false"}
This will check each element of the dataArray and if the elements isPurchased is "false" it will keep it
You can use filter with contains function
Model Class:
class PlanModel {
var isPurchased:String?
var planName:String?
init(isPurchased:String?, planname:String?) {
self.isPurchased = isPurchased
self.planName = planname
}
}
override func viewDidLoad() {
super.viewDidLoad()
var plan = [PlanModel]()
plan.append(PlanModel(isPurchased: "true", planname: "Question"))
plan.append(PlanModel(isPurchased: "true", planname: "Personal"))
plan.append(PlanModel(isPurchased: "false", planname: "Full"))
// Filter function
plan = plan.filter {
($0.isPurchased?.contains("false"))!
}
print(plan.count)
// 1
}
Create a filtering function:
func notPurchased(planModel: PlanModel) -> Bool{
return planModel.isPurchased == "false"
}
and use the Array filter function passing in your function
let filteredArray = dataArray.filter(notPurchased)
After post my solution, let me tell you that it's better change isPurchased type from String to Bool.
And now...
class PlanModel
{
var isPurchased:String?
var planName:String?
}
let p1: PlanModel = PlanModel()
p1.isPurchased = "true"
p1.planName = "Question"
let p2: PlanModel = PlanModel()
p2.isPurchased = "true"
p2.planName = "Personal"
let p3: PlanModel = PlanModel()
p3.isPurchased = "false"
p3.planName = "Full"
var plans: [PlanModel] = [ p1, p2, p3 ]
// Filter elements with `isPurchased` property
// set to `true`. As isPurchased is marked as an
// `Optional` type I check that it's not nil before
// process it
plans = plans.filter()
{
guard let isPurchased = $0.isPurchased else
{
return false
}
return isPurchased == "true"
}
plans.forEach()
{
if let planName = $0.planName
{
print(planName)
}
else
{
print("unnamed")
}
}
Since you're looking for removing the item from array itself if it meets certain condition you can do the following code:
dataArray = dataArray.filter({ $0.isPurchased == "False"})
i find this is one of the best approaches and i was using Swift 3
Now on the side note, i recommend using structs instead of classes for models

Group elements with the same property value from an array [duplicate]

This question already has answers here:
How to group by the elements of an array in Swift
(16 answers)
Closed 6 years ago.
I have an array [modelA,modelB,modelC,modelD,modelE], each element in the array is an instance of a Struct. The Struct has a property "name". for example...
modelA.name = "abc"
modelB.name = "efg"
modelC.name = "hij"
modelD.name = "abc"
modelE.name = "efg"
How can I group elements with the same property value into a new array? i.e. put modelA and modelD into a new array,and put modelB and modelE into another array.
Assume the original array is large.
You can achieve this by using filter(_:):
Returns an array containing, in order, the elements of the sequence
that satisfy the given predicate.
For example, consider that the structure looks like:
struct Model {
var name: String?
}
And you have an array of models:
let allModelsArray = [Model(name: "abc"), Model(name: "efg"), Model(name: "hij"), Model(name: "abc"), Model(name: "efg"), Model(name: "efg"), Model(name: "hij")]
So, you can get your arrays by doing (assuming that you want to filter based on the value of the name):
let abcModelsArray = allModelsArray.filter { $0.name == "abc" }
// [Model(name: Optional("abc")), Model(name: Optional("abc"))]
let hijModelsArray = allModelsArray.filter { $0.name == "hij" }
// [Model(name: Optional("hij")), Model(name: Optional("hij"))]
ALSO:
You mentioned that:
how can I put element which has the same property value into a new
array, such as put modelA and modelD into a new array, and put modelB
and modelE into a new array, if array is large.
Somehow, you might want to use the lazy version of the collection.
Hope this helped.
I have not performance tested this
struct Model {
var type : String
var name : String
}
var modelA = Model(type: "A", name: "abc")
var modelB = Model(type: "B", name: "efg")
var modelC = Model(type: "C", name: "abc")
var modelD = Model(type: "D", name: "efg")
let models = [modelA,modelB,modelC,modelD]
let names = Set(models.map({return $0.name}))
var groupedModels : [String:[Model]] = [:]
for var name in names {
let elements = models.filter({$0.name == name})
groupedModels[name] = elements
}
.reduce solution:
let a = [modelA, modelB, modelC, modelD, modelE]
let arr = a.reduce([:]) { (result, currentModel) -> [String: [Model]] in
var mutableDic = result
if ((mutableDic[currentModel.name]) != nil) {
mutableDic[currentModel.name]?.append(currentModel)
} else {
mutableDic[currentModel.name] = [currentModel]
}
return mutableDic
}
It will return the same dictionary as #Grimxn response. or got from this for loop
var mutableDic = [String : [Model]]()
for aModel in a {
if ((mutableDic[aModel.name]) != nil) {
mutableDic[aModel.name]?.append(aModel)
} else {
mutableDic[aModel.name] = [aModel]
}
}
The key is to use a Dictionary to track for Model that need to be put in the same array, by comparing to it's .name.

Swift: array of objects search

I want to search in array of objects in swift
but I didn't know how :(
I tried
filteredArrayUsingPredicate
but still don't work ,It's giving me an error msg
-- Update --
the error message is
swift:42:9: 'Array<search_options>' does not have a member named 'filteredArrayUsingPredicate'
-- Update --
class search_options {
let id:String
let option:String
init(){}
init(id:String ,option:String){
self.id = id
self.option = option
}
}
I only want to search in option variable
And when I tried to used
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0 == "test" }
println(searchBar.text)
}
I got this message
swift:40:58: 'search_options' is not a subtype of 'String'
Find index of specific object:
if let index = find(myArray, objectIAmLookingFor) {
// found! do something
}
Filter array:
let filteredArray = filter(myArray) { $0 == objectIAmLookingFor }
Finally after long search I did't ! ,
I was looking to find a way to do a dynamic search like if array of String contains
"hello","lo","yes"
and I want to get all the strings that contains for example "lo"
I want to get "hello" and "lo"
so the best way I found is regular expression search
so I do a For Loop throw all options in Array and compare every single object variable to the pattern ,and save it in new array on objects
for var i = 0; i < search_options_array.count; i++ {
let myRegex = "searched_text"
if let match = search_options_array[i].option.rangeOfString(myRegex, options: .RegularExpressionSearch){
filtered_options_array.append(search_options(id:search_options_array[i].id,option:search_options_array[i].option) )
}
}
The best part here you can use all benefits of regular expression and have a copy of yours old array so if you need it.
Thanks every one for helping.
Because filter accepts as a predicate a function which maps each element of the given Array to a Bool value (to determine which value should be filtered out), in your case it may be this way;
let a = [
search_options(id: "a", option: "X"),
search_options(id: "b", option: "Y"),
search_options(id: "c", option: "X")
]
let b = filter(a) { (e: search_options) in e.option == "X" }
// ==> [search_options(id: "a", option: "X"), search_options(id: "c", option: "X")]
The correct answer is
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.option == "test" }
println(searchBar.text)
}
or
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.id == "test" }
println(searchBar.text)
}
You must retrieve property of searched object by which you perform searching

Find Object with Property in Array

is there a possibility to get an object from an array with an specific property? Or do i need to loop trough all objects in my array and check if an property is the specific i was looking for?
edit: Thanks for given me into the correct direction, but i have a problem to convert this.
// edit again: A ok, and if there is only one specific result? Is this also a possible method do to that?
let imageUUID = sender.imageUUID
let questionImageObjects = self.formImages[currentSelectedQuestion.qIndex] as [Images]!
// this is working
//var imageObject:Images!
/*
for (index, image) in enumerate(questionImageObjects) {
if(image.imageUUID == imageUUID) {
imageObject = image
}
}
*/
// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
var imageObject = questionImageObjects.filter( { return $0.imageUUID == imageUUID } )
// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
You have no way to prove at compile-time that there is only one possible result on an array. What you're actually asking for is the first matching result. The easiest (though not the fastest) is to just take the first element of the result of filter:
let imageObject = questionImageObjects.filter{ $0.imageUUID == imageUUID }.first
imageObject will now be an optional of course, since it's possible that nothing matches.
If searching the whole array is time consuming, of course you can easily create a firstMatching function that will return the (optional) first element matching the closure, but for short arrays this is fine and simple.
As charles notes, in Swift 3 this is built in:
questionImageObjects.first(where: { $0.imageUUID == imageUUID })
Edit 2016-05-05: Swift 3 will include first(where:).
In Swift 2, you can use indexOf to find the index of the first array element that matches a predicate.
let index = questionImageObjects.indexOf({$0.imageUUID == imageUUID})
This is bit faster compared to filter since it will stop after the first match. (Alternatively, you could use a lazy sequence.)
However, it's a bit annoying that you can only get the index and not the object itself. I use the following extension for convenience:
extension CollectionType {
func find(#noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
return try indexOf(predicate).map({self[$0]})
}
}
Then the following works:
questionImageObjects.find({$0.imageUUID == imageUUID})
Yes, you can use the filter method which takes a closure where you can set your logical expression.
Example:
struct User {
var firstName: String?
var lastName: String?
}
let users = [User(firstName: "John", lastName: "Doe"), User(firstName: "Bill", lastName: "Clinton"), User(firstName: "John", lastName: "Travolta")];
let johns = users.filter( { return $0.firstName == "John" } )
Note that filter returns an array containing all items satisfying the logical expression.
More info in the Library Reference
Here is a working example in Swift 5
class Point{
var x:Int
var y:Int
init(x:Int, y:Int){
self.x = x
self.y = y
}
}
var p1 = Point(x:1, y:2)
var p2 = Point(x:2, y:3)
var p3 = Point(x:1, y:4)
var points = [p1, p2, p3]
// Find the first object with given property
// In this case, firstMatchingPoint becomes p1
let firstMatchingPoint = points.first{$0.x == 1}
// Find all objects with given property
// In this case, allMatchingPoints becomes [p1, p3]
let allMatchingPoints = points.filter{$0.x == 1}
Reference:
Trailing Closure
Here is other way to fetch particular object by using object property to search an object in array.
if arrayTicketsListing.contains({ $0.status_id == "2" }) {
let ticketStatusObj: TicketsStatusList = arrayTicketsListing[arrayTicketsListing.indexOf({ $0.status_id == "2" })!]
print(ticketStatusObj.status_name)
}
Whereas, my arrayTicketsListing is [TicketsStatusList] contains objects of TicketsStatusList class.
// TicketsStatusList class
class TicketsStatusList {
internal var status_id: String
internal var status_name: String
init(){
status_id = ""
status_name = ""
}
}

Resources