I have an array named arr of type [Int8]:
var arr: [Int8] = []
Throughout the program I add items to the array using append and insert. However, when I try to remove an item using arr.removeIndexAt(x), it throws the error:
Playground execution failed: <EXPR>:144:13: error: immutable value of type '[Int8]'
only has mutating members named 'removeAtIndex'
arr.removeAtIndex(x)
Why is this happening? I tried recreating this in a playground:
var arr: [Int8] = []
arr.append(1)
arr.removeAtIndex(0)
and it works fine. Could someone please explain to me how I might fix this problem or remove an item another way? Any help wold be great. Thanks :)
Found the solution. Add mutating to your definition of removeExtraZeros() to allow it to alter properties, i.e,
mutating func removeExtraZeros() { ... }
Unfortunately you run into an issue where the while loop after that for loop is looping infinitely, so consider revising that part as well.
You say when you try to remove an item using arr.removeIndexAt(x), it throws the error.
Because the method name is removeAtIndex:, not removeIndexAt:
Related
As #vadian suggested, I am learning Xcode from Paul Hudson's 100 days of SwiftUI to better understand the basics (even though I am still struggling with time to deliver working GitHub repository search - no it is not for the job I am working on right now).
I am doing a lesson on Arrays, so pretty basic stuff right now and I struggle to map the String from array on the sorted array. I don't get why, but I get the:
Ambiguous use of 'init'
error.
Here's the code:
let cities = ["London", "Tokyo", "Rome", "Budapest"]
print(cities.sorted())
let citiesSorted = cities.sorted()
let citiesSortedString = citiesSorted.map(String.init).joined(separator:", ")
And it's so really strange, since I pulled the similar thing out before in the same Playground but not with the sorted Array:
var schoolScoresString = schoolScores.map(String.init).joined(separator:", ")
print(schoolScoresString)
And yes I tried changing let to var. It didn't help.
cities is already of type [String], so you're passing a String to String.init, which obviously won't work. If you want to join an array of Strings into a single String, remove the map and just call joined on the array.
let citiesSortedString = citiesSorted.joined(separator:", ")
Scala beginner who is trying to store values obtains in a Scala foreach loop but failing miserably.
The basic foreach loop looks like this currently:
order.orderList.foreach((x: OrderRef) => {
val references = x.ref}))
When run this foreach loop will execute twice and return a reference each time. I'm trying to capture the reference value it returns on each run (so two references in either a list or array form so I can access these values later)
I'm really confused about how to go about doing this...
I attempted to retrieve and store the values as an array but when ran, the array list doesn't seem to hold any values.
This was my attempt:
val newArray = Array(order.orderList.foreach((x: OrderRef) => {
val references = x.ref
}))
println(newArray)
Any advice would be much appreciated. If there is a better way to achieve this, please share. Thanks
Use map instead of foreach
order.orderList.map((x: OrderRef) => {x.ref}))
Also val references = x.ref doesn't return anything. It create new local variable and assign value to it.
Agree with answer 1, and I believe the reason is below:
Return of 'foreach' or 'for' should be 'Unit', and 'map' is an with an changed type result like example below:
def map[B](f: (A) ⇒ B): Array[B]
Compare To for and foreach, the prototype should be like this
def foreach(f: (A) ⇒ Unit): Unit
So If you wanna to get an changed data which is maped from your source data, considering more about functions like map, flatMap, and these functions will traverse all datas like for and foreach(except with yield), but with return values.
I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).
var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
]
I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like
colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
The line above doesn't work, it is just to illustrate what I need.
Thanks for any help
Update: the code above is an example. Below the real code:
var placedBeacons : [BeaconStruct] = []
BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in
for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item
}
})
Error: Cannot subscript a value of type '[BeaconStruct]' with an index of type String
To match the key subscripting
self.placedBeacons["\(item.major):\(item.minor)"] = item
you have to declare placedBeacons as dictionary rather than an array
var placedBeacons = [String:BeaconStruct]()
It requires that item is of type BeaconStruct
The code you wrote, it should work. I have used such kind of code and was able to implement successfully. I just tested your code in my end and it's working for me. I declared colors variable globally in my class file and in view did load method added the second code to add another item in my colors array. After printing it out. My output shows full list of array with 4 items and the number of array count return 4 as well.
Please let me know, more details of your scenario so i can help you to figure it out the issue. but looks like it should work.
ArrayList<Qubit> cycl = new ArrayList<Qubit>();
Qubit num0 = new Qubit(4,5,6,64);
cycl.add(num0);
has error identifier expected. Can you please help?
A few things to try:
Try specifying the type of object to go into the ArrayList: ArrayList<Qubit> cycl = new ArrayList<Qubit>();
Make sure you are importing java.util.ArrayList
Make sure you are calling the constructor correctly
I am trying to create an empty array in Swift that the user adds on to. It is a very small class because I am just starting a new file. I am using this tutorial for my project which is what the code is based off. Here is the code I tried (It didn't work):
var tasks = task[]()
Here is all of my code in case it is needed:
class TaskManager: NSObject {
var tasks = task[]()
func addTask(name: String){
tasks.append(task(name: name))
}
}
There is an error on the var tasks = task[]() line saying: "Array types are now written the brackets around the element type". I am unsure of how to fix the problem.
How can one create an empty array?
Any input or suggestions would be greatly appreciated.
Thanks in advance.
You have to declare the array in this way:
var tasks = [task]()
It changed in swift from the tutorial you are watching.
The syntactic sugar for an array of Type is [Type] in Swift. You can create an empty array of Tasks like this:
class Task{}
var tasks = [Task]()