Swift: Adding more elements to my append - arrays

I am wondering how to add more elements to my array 'faq'. right now it has just image but i want to string a label and other images. This is Xcode Swift.
var questions : [faq] = faq
var selectQuest = 0;
var doneQuest = Bool()
override func viewDidLoad() {
super.viewDidLoad()
questions.append(faq(fImage: "1.png") here x) or X<-- I guess in here where ar you add more elements?
questions.append(faq(fImage: "2.png"))
questions.append(faq(fImage: "3.png"))
questions.append(faq(fImage: "4.png"))
questions.append(faq(fImage: "5.png"))
questions.append(faq(fImage: "6.png"))
questions.append(faq(fImage: "7.png"))
questions.append(faq(fImage: "8.png"))
dispendserIQGCollectionView.reloadData()
print(questions.count)

See the Swift Documentation: Collection Types.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

If I understand your question correctly, you have an array of FAQ. The FAQ class has an member named fImage. However, you want to add more members to class.
I think your class looks something like this -
class FAQ {
var fImage: UIImage
/*Rest of class*/
}
To add more member to the class, you need to add another member named fLabel to the class, as shown below
class FAQ {
var fImage: UIImage
var fLabel: UILabel
/*Rest of class*/
}

Related

Unable to append string to mutable array in Swift

Context - I'm currently learning Swift Struct. So I decided to create my own Phone structure in Playground. (see below)
Problem -
The downloadApp method on the phone struct is throwing the following error.. Cannot use mutating member on immutable value: 'self' is immutable.
Expect outcome - To peacefully append new strings to my apps property, which is an array of strings.
Swift code
struct Phone {
let capacity : Int
let Brand : Sting
var name: String
let model: String
var apps: [String]
var contacts: [String]
var formatCapacity: String {
return "\(capacity)GB"
}
func downloadApp(name: String){
apps.append(name) // ERROR
}
}
You simply need to mark downloadApp as mutating. The issue is caused by the fact that downloadApp is declared in a struct type, which is a value type and hence if you mutate any properties (namely, the apps array here) of the struct, you actually mutate the struct itself. By marking the function as mutating, the compiler allows such modification of the struct through a member function of the type.
mutating func downloadApp(name: String){
apps.append(name)
}

Xcode Swift add a value to a defined array in swift

What I'm looking to try to do is have another var attached to the array to store values in without having to make a 2D array.
var list: NSMutableArray! = NSMutableArray()
list.add("Apple")
list[0].color = red // Something like this
Any help in the right direction will be appreciated
For that make array of custom class or struct.
struct Fruit {
let name: String
let color: String
}
Now make array of this struct and add object of this struct in it.
var fruits = [Fruit]()
fruits.append(Fruit(name: "Apple", color: "red"))
Now you can access object in a way you describe in your question.
print(fruits[0].name) //Apple
print(fruits[0].color) //red
Note: In Swift use swift's type Array and Dictionary instead of NSArray and NSDictionary.

Swift Array of Self-defined Objects Contains: Requires to Insert 'where:'

Hi I'm new to Swift and I'm trying to implement a Graph structure. I have defined Node and Edge structs, and now I'm trying to check whether a particular edge exists in the graph or not. The class and related function is like this:
class Graph<T: Equatable> {
private var storedNodes = [Node]()
private var storedEdges = [Edge]()
func containsSimpleGraphEdge(targetEdge: Edge) -> Bool {
let simpleGraphEdges = self.storedEdges.map({edge in (edge.source, edge.dest)})
let targetSimpleGraphEdge = (targetEdge.source, targetEdge.dest)
return simpleGraphEdges.contains(targetSimpleGraphEdge)
}
But Xcode is complaining that I should insert 'where: ' in the last contains statement. May I know why it's like this? My purpose is just to check whether an edge exists in the graph or not. The mapping to tuples is done because in the Edge implementation there are other properties; here only the source node and the destination node need to be checked.
But Xcode is complaining that I should insert where: in the last
contains statement. May I know why it's like this?
As pointed out by #Keiwan below, tuples don't conform to Equatable, even if Swift's standard lib provides us with equality testing operator == for tuples up to 6 members, given that all members themselves conform to Equatable; the latter as described in the following Swift Evolution proposal:
Se-0015: Tuple comparison operators
Hence, your attempted call to contains(_:) fails as this method is not accessible for non-Equatable elements.
You could, however, make use of contains(where:) to explicitly provide a closure telling contains how to test equality. Given that your Node type conforms to Equatable, you'll want to modify the contains call in the return of your method into:
return simpleGraphEdges.contains(where: { $0 == targetSimpleGraphEdge })
// note also your typo here, 'targetSimpleEdge' should be 'targetSimpleGraphEdge'
Or, supplying the predicate as a trailing closure:
return simpleGraphEdges.contains { $0 == targetSimpleGraphEdge }
If you don't want to make Edge equatable (such as when it has multiple context-dependant definitions of "equality"), you can just use contains(where:).
func contains(simpleGraphEdge e: Edge) -> Bool {
return self.storedEdges.contains(where: {
$0.source == e.source && $0.dest == e.dest
})
}

SWIFT how to store a CLASS containing a STRUCT with an ARRAY of STRUCT inside USERDEFAULTS

the problem may sound weird but is exactly my situation.
I have a class containing a struct with only an array inside: an array of another struct. I would like to store an object of the class into user default. Let see some code
struct Inside {
var something: String
var somethingElse: Int
}
struct Outside {
var array = [Inside]()
}
class TheClass: {
var array = [Outside]()
}
var a = TheClass()
//now I would like to put 'a' into UserDefaults
I tried to use NSCoding, like you can see in this code (the code compiles)
class TheClass: NSObject, NSCoding {
var array: NSMutableArray = NSMutableArray()
override init(){
self.elementi = []
}
required init(coder aDecoder: NSCoder) {
elementi = aDecoder.decodeObjectForKey("elementi") as! NSMutableArray
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(elementi, forKey: "elementi")
}
}
but when I try to add an object of struct Outside into the NSMutableArray, I get an error. I found out that one solution is to convert into an NSValue. Here is the code in objective C, I am not able to translate it in swift
//here 'a' denotes an object of Outside struct that we want to insert into the NSMutableArray stored inside an object of TheClass (we cannot add it directly to the NSMutableArray)
NSValue* value = [NSValue value:&a withObjCType:#encode(Outside)];
//To extract it later:
[value getValue:&value];
I don't know how to solve this problem. Maybe I can change the struct to classes, in this way NSObject is no more need and I can use NSCoding directly (can be used with class object but not with struct object). But if I do this way I will get exactly the error that this guy have: SWIFT: Copying objects from arrays then changing properties and adding them back to original array
What do you suggest?

Swift Array.filter method

Swift's filter method is defined as follows:
func filter(includeElement: (T) -> Bool) -> [T]
Why does filter definition in Swift's array does not have <T> in its definition (i.e. filter(...))?
filter is a method of the Array<T> class, so T is specified at class level and there is no need to replicate that in the method - actually doing that at method level is a mistake:
struct Array<T> ... {
func filter<V>(includeElement: (V) -> Bool) -> [V]
}
because V is a different type that has no relationship with T (unless you set constraints in the generic definition). By mistake I mean T and V are different types, whereas it could be thought they are the same. Having a generic class with a generic method is perfectly legit though.
it is because this function is defined in an extension to Array struct and the definition of Array has the in its definition : struct Array
class AA<T> {
}
extension AA {
func something(aThing: T) -> T{
return aThing
}
}

Resources