Home > Enterprise >  for-in loop requires 'Int' to conform to 'Sequence'
for-in loop requires 'Int' to conform to 'Sequence'

Time:01-08

I have a function descendingOrder and input number (Int)

func descendingOrder(of number: Int) -> Int {
    var arr = [Int]()
    for n in number{
      arr.append(n)
    }
}

I want from number to make an array with single digits of that number. I have an error: for-in loop requires 'Int' to conform to 'Sequence'

Can someone help me and explain to me what this error means? Thank you

CodePudding user response:

The error means that the for loop requires a sequence of things, such as a range, but you are giving it a single number.

Try this:

func descendingOrder(of number: Int) -> [Int] {  // <-- here
    var arr = [Int]()
    for n in 0..<number {  // <-- here to avoid your error
      arr.append(n)
    }
    return arr // <-- here
}

CodePudding user response:

I want from number to make an array with single digits of that number.

Unlike String which is built up of single Characters and therefore can conform to Sequence the Int type cannot be represented by an array of Digit. There is no such API because the computer doesn't think in base10.

The return value of your function is wrong anyway, according to your request you want an array which is [Int]

A possible way to split an Int into digits is math, a combination of getting the remainder of a division by 10 and division by 10 itself in a loop until the value reaches zero. It's actually a base10 version of the shift right operator (>>).

func descendingOrder(of number: Int) -> [Int] {
    if number < 0 { return [] } // return an empty array if the number is negative
    var arr = [Int]()
    var num = number // make number mutable
    while num > 0 { // exit the loop when num is zero
        // to reverse the order you have to insert the remainder at front.  
        arr.insert(num % 10, at: 0)
        // divide num by 10
        num /= 10
    }
    return arr
}

let d = descendingOrder(of: 624) // [6, 2, 4]

CodePudding user response:

I'm not sure if I understand what you mean or not. This is how I descending 1 number. Hope to help you.

func descendingOrder(of number: Int) -> Int {
    let digits = "\(number)".compactMap {Int("\($0)")}.sorted(by: {$0 > $1})
    let string = digits.compactMap {"\($0)"}.reduce("",  )
    if let output = Int(string) {
        return output
    }
    
    return number
}

CodePudding user response:

Try converting number to a string like this:

func descendingOrder(of number: Int) -> Int {
    var arr = [Int]()
    for n in "\(number)" {
        arr.append(n)
    }
    return arr
}

The error "requires 'Int' to conform to 'Sequence'" has appeared because swift is expecting a sequence (something that you can iterate over such as an array, a string, or a range). The definition of the sequence protocol is explained here.

  • Related