Home > OS >  How to calculate height based on item count in swift
How to calculate height based on item count in swift

Time:09-22

How do I archive this result using a simple mathematical formula.

I have an initial offset = 100, and initial count = 0, that i want to increase the offset based on count value. I tried using the below code but it doesn't function correctly.

Example

  1. When count is 0 to 3, then offset should be 100.
  2. When count is 4 to 6, then offset should be 200.
  3. When count is 7 to 9, then offset should be 300.
  4. When count is 10 to 12, then offset should be 400.

Attempt

func getHeight(count: Int) ->CGFloat {
     var index = 0
     for i in 0..<count{
         if(i % 2  != 0){
             index  = 1
         }
     }
    return CGFloat(100 * index)
    //return CGFloat(count   3 / 9 * 100)
}

Testing

print("0 to 3 = \(self.getHeight(count: 0)), expected = 100")
print("0 to 3 = \(self.getHeight(count: 2)), expected = 100")
print("4 to 6 = \(self.getHeight(count: 4)), expected = 200")
print("7 to 9 = \(self.getHeight(count: 7)), expected = 300")
print("10 to 12 = \(self.getHeight(count: 12)), expected = 400")

Results

0 to 3 = 0.0, expected = 100
0 to 3 = 100.0, expected = 100
4 to 6 = 200.0, expected = 200
7 to 9 = 300.0, expected = 300
10 to 12 = 600.0, expected = 400

CodePudding user response:

Formula with integer division:

let cnt = count != 0 ? count : 1
result = 100 * ((cnt   2) / 3)
  • Related