How to append custom object to an array in Swift? - arrays

How to append custom class object to an array in Swift?
Below is my code, but it shows error.
Error:
"Cannot assign value of '()' to type [PhotoVC]"
Code:
var photoVCs = [PhotoVC]()
for index in 0 ..< photos.count {
if let vc = getPhotoController(index) {
photoVCs = photoVCs.append(vc)
}
}
func getPhotoController(index: Int) -> PhotoVC? {
if index < 0 || index == NSNotFound {
return nil
}
else if index == photos.count {
return nil
}
let PhotoVCID = "PhotoVCID"
if let storyboard = storyboard,
pageVC = storyboard.instantiateViewControllerWithIdentifier(PhotoVCID) as? PhotoVC {
pageVC.photoName = photos[index]
pageVC.photoIndex = index
return pageVC
}
return nil
}
I should be able to do it, but what's the problem?

append does not return anything. Remove the assignment:
photoVCs = photoVCs.append(vc) // wrong
photoVCs.append(vc) // ok

Related

Fix "Type of expression is ambiguous without more context"

I have this code:
let index = findIndex(array: soldierCanFire, valueToFind: (firstBody.node? ?? default value) as Soldier)
if(index != nil){
soldierCanFire.removeAtIndex(index!)
}
func findIndex<T: Equitable>(array: [T], valueToFind: T) -> Int?{
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
I have seen some guides but I have not fully understood what kind of error it is and how to fix it
The modern syntax is
if let soldier = firstBody.node as? Soldier,
let index = soldierCanFire.firstIndex(where: {$0 == soldier}) {
soldierCanFire.removeAtIndex(index)
}
The custom method is not needed.
And even with your method it’s
if let soldier = firstBody.node as? Soldier,
let index = findIndex(array: soldierCanFire, valueToFind: soldier) {
soldierCanFire.removeAtIndex(index)
}

Adding string to array

When i am parsing through the string from the url, I append each new line to an array. However I only want to add if the field is not empty. So if the column[5] is an empty string I don't append it to the array. For example I have two lines of strings:
1,2,3,4,5,
1,2,3,4,5,6
I only want to append when there are 6
However I am getting a index out of range error on the if column[5] == "" line
func readDataFromURL(url: String) -> String?{
if let url = URL(string: url)
{
do {
var contents = try String(contentsOf: url)
contents = contents.replacingOccurrences(of: "\r", with: "")
csv(data: contents)
return contents
} catch {
print("File error \(url)")
return nil
}
}
return nil
}
func csv(data: String) -> [[String]] {
var result: [[String]] = []
let rows = data.components(separatedBy: "\n")
for row in rows {
let columns = row.components(separatedBy: ",")
if columns[5] == "" {
continue
} else {
result.append(columns)
}
}
return result
}
Your current code will crash if num of elements is less than 6 , Replace
if columns[5] == "" {
continue
} else {
result.append(columns)
}
with
if columns.count > 5 && columns.last != "" {
result.append(columns)
}

Value of type '[Double]?' has no member 'append'

I have the following problem:
Value of type '[Double]?' has no member 'append'
My code:
var values : [Double]?
if (value.string == nil) {
values = (dataChart[key])!
values.append(Double.nan)
dataChart[key] = values
} else {
values = dataChart[key]!
values.append(Double(value.int!))
dataChart[key] = values
}
Use Optional Chaining to append a value to an optional array. And avoid force unwrapping. Since values array is declared as an optional, you don't need to force unwrap dataChart[key]!. Just use dataChart[key]
if value.string == nil {
values = dataChart[key]
values?.append(Double.nan)
dataChart[key] = values
} else {
values = dataChart[key]
if let intValue = value.int {
values?.append(Double(intValue))
}
dataChart[key] = values
}
you need to append with a for
and you have to save it in an array
var resultArray: [RegisterObject] = []
example:
for register in results {
let obj = RegisterObject()
obj.celNumber = register.celNumber
obj.dv = register.dv
obj.gId = register.gId
resultArray.append(obj)
}

Find element in an array of object

I created an array of objects:
var fullMonthlyList = [SimulationMonthly]()
The class here:
class SimulationMonthly {
var monthlyMonthDuration: NSNumber = 0
var monthlyYearDuration: NSNumber = 0
var monthlyFullAmount: NSNumber = 0
var monthlyAmount: Int = 0
init(monthlyMonthDuration: NSNumber, monthlyYearDuration: NSNumber, monthlyFullAmount: NSNumber, monthlyAmount: Int){
self.monthlyMonthDuration = monthlyMonthDuration
self.monthlyYearDuration = monthlyYearDuration
self.monthlyFullAmount = monthlyFullAmount
self.monthlyAmount = monthlyAmount
}
}
I just did append to populate it, now I want to find for example if they're an existing value, for example monthlyAmount equals to "194" by search in the array, how can I do ? I have tried filter and contains but I get errors.
What I've tried:
if self.fullMonthlyList.filter({ $0.monthlyAmount == self.monthlyAmount.intValue }) { ... }
Error:
Cannot invoke 'filter' with an argument list of type '((SimulationMonthly) throws -> Bool)'
You can do:
if let sim = fullMonthlyList.first(where: { $0.monthlyAmount == 194 }) {
// Do something with sim or print that the object exists...
}
This will give you the first element in your array where monthlyAmount equals 194.
If you want all elements with that condition, you can use filter:
let result = fullMonthlyList.filter { $0.monthlyAmount == 194 }
If you don't need the object at all but you just want to know if one exists, then contains would be enough:
let result = fullMonthlyList.contains(where: { $0.monthlyAmount == 194 })
Here's a simple playground example of filtering objects based on matching a property. You should be able to expand it to your situation.
class Item {
var value: Int
init(_ val: Int) {
value = val
}
}
var items = [Item]()
for setting in 0..<5 {
items.append(Item(setting))
}
func select(_ with: Int) -> [Item] {
return items.filter { $0.value == with }
}
let found = select(3)

Arrays and Swift

I'm trying to deal with an app in Swift and I'm facing the following error using arrays:
fatal error: Array index out of range
This appears when apps assign a value to the array at index 0:
class DrawScene: SKScene {
init(size: CGSize) {
super.init(size: size)
}
var line = SKShapeNode()
var path = CGPathCreateMutable()
var touch: UITouch!
var pts = [CGPoint]()
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
touch = touches.anyObject() as UITouch!
self.pts[0] = touch.locationInNode(self) <-- Error appears here
drawLine()
}
Some ideas? (I'm using xcode 6 Beta 4)
Your array is empty at first.
if self.pts.isEmpty {
self.pts.append(touch.locationInNode(self))
}
else {
self.pts[0] = touch.locationInNode(self)
}
As it says in the docs:
“You can’t use subscript syntax to append a new item to the end of an array. If you try to use subscript syntax to retrieve or set a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error.”
You'll have to use append or += to add to an empty array. If you always want to set this point to the first object in the array, replacing anything already there, you'll have to check the count of the array first.
I don't recommend this to anyone, but you could implement your own subscript that allows you to do this:
extension Array {
subscript(safe index: Int) -> Element? {
get {
return self.indices.contains(index) ? self[index] : nil
}
set(newValue) {
guard let newValue = newValue { return }
if self.count == index {
self.append(newValue)
} else {
self[index] = newValue
}
}
}
}
And you can use this as expected:
var arr = [String]()
arr[safe: 0] = "Test"
arr[safe: 1] = "Test2"
print(arr) // ["Test", "Test2"]
arr[safe: 0] = "Test0"
print(arr) // ["Test0", "Test2"]
arr[safe: 3] = "Test2" // fatal error: Index out of range

Resources