Hello I am new to coding and in seek of help. Lately i've been trying to make it so in a label if it get's to a certain number in my case 8 it resets back to 0.
let label = UILabel()
var count: Int = 0 {
didSet {
if count == 8 {
count = 0
}
label.text = "\(count)"
}
}
all you need to do is to increment the count where you need, everything else is taking care of by the didSet - reseting count and updating label text.
increment your count as:
count += 1 // or the value you need
Related
I want to display an average for all values that are inputted into an Entity. Basically, one would press add on the TableView and a pop up would appear asking for a score, which would then add that “exam” to the tableview. I want to be able to add up all the scores and receive an average for them which i can then add to a label. I’ve tried following some other tutorial but it gives me an error.
https://i.stack.imgur.com/P7exB.jpg
https://i.stack.imgur.com/WWITI.jpg
The images above are for context.
var i = 0
var sum = 0
for i in 0...methodsExam.count {
let title = methodsExam[i]
let str : String = title.value(forKey: "score") as! String
sum = sum + Int(str)!
}
let avg = sum/methodsExam.count
averageScore.text = "Average: \(avg)"
Assuming methodsExam is an array of [MethodsExam] you can change the loop to
var sum = 0.0
for item in methodsExam {
if let scoreStr = item.score, let score = Double(scoreStr) {
sum += score
}
}
let average = sum / Double(methodsExam.count)
I am using Double here for more precision.
This could also be done with a high-order function
let average = methodsExam.reduce(into: 0.0) {
if let scoreStr = $1.score, let score = Double(scoreStr) { $0 += score }
} / Double(methodsExam.count)
Since we are dividing with the array count we must also check that the array isn't empty to avoid division by 0, so we can put the code into a function and do this
func calculateAverage(_ array: [MethodsExam]) -> Double {
guard !array.isEmpty else { return 0.0 }
return array.reduce(into: 0.0) {
if let scoreStr = $1.score, let score = Double(scoreStr) { $0 += score }
} / Double(array.count)
}
One caveat, I assumed that score can be nil because of MethodsExam being an NSManagedObject and not because it will hold nil values. If it indeed can hold nil values then you need to consider what to calculate the average on, all values in the array or only non-nil values.
Hi I'm stuck trying to solve this:
class Classy, to represent how classy someone or something is. "Classy". If you add fancy-looking items, "classiness" increases!
Create a method, addItem() in Classy that takes a string as input, adds it to the "items" array and updates the classiness total.
Add another method, getClassiness() that returns the "classiness" value based on the items.
The following items have classiness points associated with them:
"tophat" = 2
"bowtie" = 4
"monocle" = 5
Everything else has 0 points.
The sum is not performing correctly.
The first problem is when it falls in te default case, everything is 0, I've tried in the default with:
default:
self.classiness += 0
and I got 2 for every case
I've tried to sum the total inside in each case, and return the total but got the same result.
This is my last version
class Classy {
var items: [String]
var classiness: Int
init() {
self.items = []
self.classiness = 0
}
func addItem(_ item: String) {
var total = 0
self.items.append(item)
total += classiness
}
func getClassiness() -> Int {
switch items {
case ["tophat"]:
self.classiness = 2
case ["bowtie"]:
self.classiness = 4
case ["monocle"]:
self.classiness = 5
default:
self.classiness = 0
}
return self.classiness
}
}
let me = Classy()
print(me.getClassiness())
me.addItem("tophat")
print(me.getClassiness())
me.addItem("bowtie")
me.addItem("jacket")
me.addItem("monocle")
print(me.getClassiness()) //This would be 11
Your switch case need update, it need to loop and the case is String not Array
func getClassiness() -> Int {
var total = 0
for item in items{
switch item {
case "tophat":
total += 2
case "bowtie":
total += 4
case "monocle":
total += 5
default:
total +=0
}
}
self.classiness = total
return self.classiness
}
I'm trying to write a function that has arrayOne, arrayTwo, and arrayThree as inputs. If arrayTwo has any 0s as its last elements, the function is supposed to remove these elements from the array, as well as the same elements from arrayOne. When I run the code and try to test it, I get the error: "Terminated by signal 4".
What could the problem be?
var arrayOneNew = arrayOne
var arrayTwoNew = arrayTwo
var arrayThreeNew = arrayThree
var endElement = arrayTwoNew.last
if endElement == 0 {
var counter = arrayTwoNew.count
while arrayTwoNew[counter] == 0 {
var elementToBeRemoved = arrayTwoNew.remove(at: counter - 1)
var 2ndElementToBeRemoved = arrayOneNew.remove(at: counter - 1)
}
}
Your main problem is that you are setting counter to arrayTwoNew.count which is 1 bigger than the last valid index in arrayTwoNew, so while arrayTwoNew[counter] == 0 crashes with index out of range.
Also:
var elementToBeRemoved = arrayTwoNew.remove(at: counter - 1)
is probably meant to remove the last item from arrayTwoNew, but that is more easily accomplished with:
arrayTwoNew.removeLast()
especially since you're not using elementToBeRemoved.
I think you're trying to do this:
while arrayTwoNew.last == 0 {
arrayTwoNew.removeLast()
arrayOneNew.removeLast()
arrayThreeNew.removeLast()
}
You are creating a new array "arrayTwoNew" which is mixed up with the original one at
var arrayTwoNew = arrayTwoNew.remove(at: counter - 1)
Now I'm also struggling with your .remove - this returns an element so won't work. I'd usually use a filter here but I'm not sure what you are doing!
//code with remove taken out (replace with filter?) to get you started:
let arrayOne = [1,2,3]
let arrayTwo = [2,3,4]
let arrayThree = [5,6,7]
var arrayOneNew = arrayOne
var arrayTwoNew = arrayTwo
var arrayThreeNew = arrayThree
var endIndex = arrayTwoNew.last
if endIndex == 0 {
let counter = arrayTwoNew.count
// arrayTwoNew = arrayTwoNew.remove(at: counter - 1)
while arrayTwoNew[counter] == 0 {
// arrayOneNew = arrayOneNew.remove(at: counter - 1)
}
}
I am pretty Newbie to programming. And I am trying to pile up the random blocks dynamically till it hits the upper frame. But it seems that Swift doesn't let me to do so. Did I miss anything please? Any input are appreciated.
let blocks =[block1,block2,block3,block4,block5,block6,block7,block8,block9,block10,block11,block12]
var block:SKSpriteNode!
let blockX:Double = 0.0
var blockY:Double = -(self.size.height/2)
repeat{
block = blocks.randomBlock()
block.zPosition = 2
block.position = CGPoint(x:blockX, y:blockY)
block.size.height = 50
block.size.width = 50
self.addChild(block)
blockY += 50
} while( block.position.y < self.size.height)
extension Array {
func randomBlock()-> Element {
let randint = Int(arc4random_uniform(UInt32(self.count)))
return self[randint]
}
}
you need to have someway of tracking which blocks have been selected and ensure that they don't get selected again. The method below uses an array to store the indexes of selected blocks and then uses recursion to find a cycle through until an unused match is found.
private var usedBlocks = [Int]()
func randomBlock() -> Int {
guard usedBlocks.count != blocks.count else { return -1 }
let random = Int(arc4random_uniform(UInt32(blocks.count)))
if usedBlocks.contains(random) {
return randomBlock()
}
usedBlocks.append(random)
return random
}
in your loop change your initializer to
let index = randomBlock()
if index > -1 {
block = blocks[index]
block.zPosition = 2
block.position = CGPoint(x:blockX, y:blockY)
}
remember that if you restart the game or start a new level, etc. you must clear all of the objects from usedBlocks
usedBlocks.removeAll()
var numberOfPeople = 1 //get from host
var numberAtCounter = 0
func showNames() {
if peopleInMatch[numberAtCounter] == yourPeerID { //change to peopleinmatcheveryone
if numberOfPeople == 0 {
print("hoho")
personName.isHidden = true
connect.isHidden = false
connect.setTitle("PRESS READY", for: UIControlState.normal)
//change label to ready
} else {
numberAtCounter += 1
numberOfPeople -= 1 // buggy?
print("\(numberAtCounter)")
showNames()
}
} else {
personName.text = "TAKE PHOTO OF \(peopleInMatch[numberAtCounter])'s COLOR"
numberAtCounter += 1
if numberOfPeople <= 0 {
personName.isHidden = true
connect.isHidden = false
connect.setTitle("PRESS READY", for: UIControlState.normal)
//change label to ready
}
numberOfPeople -= 1 //buggy maybe fixed
}
}
I'm getting a Thread 1: EXC_BREAKPOINT error on the if peopleInMatch[numberAtCounter] == yourPeerID line. I'm not entirely sure what out of index means or what is potentially wrong. The code will be run through once then the function calls itself and on the second time through it breaks down on the line I mentioned above. I've checked all the variables and none of them are nill. Any ideas?
Here I made a short example for you to understand where your problem actually is.
ScreenShot 1:
Everything works fine when function is called for first time value at numberAtCounter is printed.
Here in first call either you are decrementing the value as numberAtCounter-=1 which take value from 0 to -1. Thus in second call when the function is called in line at:
if peopleInMatch[numberAtCounter] == yourPeerID // here you need to check value of `numberAtCounter`
make sure it's not getting a negative value or value more than your peopleInMatch array.
Thus if it becomes negative or more than count, result you will get as follows: