How to acces array of structures in structure Swift - arrays

I have the following stucture:
struct Points : Codable {
var name : String?
var interests : [Interests]
///How do i get string or array of string that is equal to all interests
var allInterestText : String ///???
}
struct Interests : Codable {
var interest : Interest?
}
struct Interest : Codable{
var name : String?
}
I've been trying to achieve that, but all my attempts have failed.

Try this for a single String:
struct Points {
// ...
var allInterestText: String {
interests.compactMap { $0.interest?.name }.joined(separator: " ")
}
}
if you decide you want an Array instead, simple change the type and remove the .joined()

Related

SwiftUI - Check if a value is present in an array

I have an array with several objects each with a name and a password. Elsewhere I have a value and I would like to check if this value is already equal to a name in the array.
In my code, if the value is not equal to a "name" value in the array, I use the add() function.
I have no idea how to do this at all. Do you have any advice or a simple code for me please?
struct Object {
var name : String
var password : String
}
struct ContentView: View {
#State var valeur : String = "x"
#State var array = [Object]()
// Let's say it's filled
var body: some View {
VStack{
Button(action: {
if ... {
self.addRow()
}
}) {
Text("Add")
}
}
}
}

How to search through struct data using UISearchBar swift 4.2

I have struct datatype which is use for decoding data
struct OtherCountry : Decodable {
let name : String
let dial_code : String
let code : String
}
struct FrequentCountry:Decodable{
let name : String
let dial_code : String
let code : String
}
I want to search based on name & code and this is stored in array of type struct
var OtherDataCountry = [OtherCountry]()
var FrequentDataCountry = [FrequentCountry]()
I have also implemented search function that looks something like this
func searchBar(searchText: String) {
searchCountry1 = OtherDataCountry.filter({ (OtherCountry) -> Bool in
return OtherCountry.name.range(of: searchText , options:[.caseInsensitive]) != nil
searchActive = !searchCountry1.isEmpty
self.mTableView.reloadData()
}
)}
}
can anyone help me to convert that struct data to String array , that would be helpful because i can search through array and use that result to show entire data .
Thank You for Help !
Please try below code
func searchBar(searchText: String) {
searchCountry1 = OtherDataCountry.filter {
$0.name.range(of: searchText , options:[.caseInsensitive]) != nil
}.map {$0.name}
searchActive = !searchCountry1.isEmpty
self.mTableView.reloadData()
}
)
}
searchCountry1 will be an array after map containing the name value

Modify an array element after finding it in swift does not work

I wrote a model like this as an exercise :
struct Store {
var name : String
var bills : Array<Bill>
var category : Category?
}
struct Bill {
var date : String
var amount : Float
}
struct Category {
var name : String
var tags : Array<String>
}
and when I'm searching if a store already exist to add a bill to it instead of creating a new store, my code doesn't work. It acts like if the result of the search is a copy of the Array element . I would like to have a reference.
var stores : Array <Store> = Array()
for billStatment in billStatements! {
let billParts = billStatment.split(separator: ",")
if billParts.count > 0 {
let bill : Bill = Bill(date:String(billParts[0]), amount: Float(billParts[2])!)
var store : Store = Store(name:String(billParts[1]), bills: [bill], category: nil)
if var alreadyAddedStore = stores.first(where: {$0.name == String(billParts[1])}) {
alreadyAddedStore.bills.append(bill)
print("yeah found it \(alreadyAddedStore)") // the debugger breaks here so I know the "first" method is working. If I print alreadyAddedStore here I have one more element, that's fine.
} else {
stores.append(store)
}
}
}
print("\(stores.count)") // If I break here for a given store that should contains multiple elements, I will see only the first one added in the else statement.
Can anyone tell me what I am doing wrong?
As already noted, you're confusing value (struct) semantics with reference (class) semantics.
One simple fix would be the change stores to a dictionary with the name as your key:
var stores : Dictionary<String, Store> = [:]
and use it like this:
if(stores[store.name] == nil) {
stores[store.name] = store
}
else {
stores[storeName].bills.append(bill)
}

How to append data from a class to a struct? Throws expected declaration

I am defining a dictionary with the values as an array. The values (inside the array) is obtained from another function and defined through JSONSerialization in a class. I need the values to be passed down to a struct (so it can be accessed globally, related to my other post https://stackoverflow.com/questions/40180767/access-value-of-variables-from-other-classes ). However, it doesn't seem to behave as a normal dictionary.
This is the whole piece of code of that particular swift file, including the class and the struct. Any help is appreciated thanks.
edit: shows where is the error
struct busStopIdentities
{
static var busStopArray : [String : [AnyObject]] = ["busStopCode_as_identifier" : ["busStopData" as AnyObject]]
}
class BusStop
{
var busStopCode : String?
var roadName : String?
var busStopDescription : String?
var busStopLatitude : Double?
var busStopLongitude : Double?
init(jsonDataDictiony : [String : AnyObject])
{
//print(jsonDataDictiony)
if let valueArray = jsonDataDictiony["value"] as? [[String : AnyObject]]
{
for valueDictionary in valueArray
{
self.busStopCode = valueDictionary["BusStopCode"] as? String
self.roadName = valueDictionary["RoadName"] as? String
self.busStopDescription = valueDictionary["Description"] as? String
self.busStopLatitude = valueDictionary["Latitude"] as? Double
self.busStopLongitude = valueDictionary["Longitude"] as? Double
}
}
}
busStopIdentities.busStopArray[busStopCode] = [busStopCode, roadName, busStopDescription, busStopLatitude, busStopLongitude]
^ expected declaration
}
A struct is not an object is a datetype, you have to create a variable, and assign to that datetype, like
var busS =
busStopIdentities(busStopArray[busStopCode]: [busStopCode, roadName, busStopDescription, busStopLatitude, busStopLongitude])
I don't know swift, so the sintax may be wrong.

add Single Value inside an existing Section in UITableView

i have a tableview with sections for adding section i created an struct :
struct datesStruct {
var sectionYear : String!
var sectionMonth : [String]!
}
var datesStructArray = [datesStruct]()
now i want to add a single value inside my exiting sections after checking if the section is satisfying my condition, any idea how am gonna do that ???
e.g. :
if myTableViewSection1 == 2016{
//add value into this section
}
searched a lot about this but didn't get anything yet , if anybody knows then please do help me thanks
First, put this function outside of your class (before "class" or after the last "}":
func == (leftItem: DatesStruct, rightItem: DatesStruct) -> Bool{
return leftItem.sectionYear == rightItem.sectionYear
}
Then Use this:
struct DatesStruct: Equatable{
var sectionYear : String!
var sectionMonth : [String]!
}
var datesStructArray = [DatesStruct]()
func addMonthToYear(year: String, month: String){
if let foundItem: DatesStruct = datesStructArray.filter({$0.sectionYear == year}).first {
datesStructArray[datesStructArray.indexOf(foundItem)!].sectionMonth.append(month)
}
}
Simply pass the year you're looking for and the month you want to add to addMonthToYear
Declare an initializer
struct datesStruct {
var sectionYear : String!
var sectionMonth : [String]!
init(sectionYear: String!, sectionMonth: [String]!) {
self.sectionYear = sectionYear
self.sectionMonth = sectionMonth
}
}
var datesStructArray = [datesStruct(sectionYear: "year", sectionMonth: ["month1", "month2"])]
Then check whether the sectionMonth contains desired string

Resources