Home > Back-end >  I want to remove out Strings from an Array
I want to remove out Strings from an Array

Time:11-23

this is my code

func filterString(array:[Any])-> [Int]{
    
    return array.remove(String)
    
    
}

CodePudding user response:

func filterString(array:[Any])-> [Any]{
        var finalArr : [Any] = []
        for i in array{
            if i is String.Type == false{
                finalArr.append(i)
            }
        }
        return finalArr
    }

CodePudding user response:

A simple filter should be enough

var arr: [Any] = ["", "", 1, 2.5]
print(arr.filter({ $0 is Int }))
// print [1]

This will return an array of Int as you seem to search for in your code. But you can also filter on only removing strings, leaving rest intact:

var arr: [Any] = ["", "", 1, 2.5]
print(arr.filter({ !($0 is String) }))
// print [1, 2.5]

CodePudding user response:

Almost

var array : [Any] = [1, "one", 2, "two", 3, "three"]
array.removeAll(where: {$0 is String})

or with your function

func filterString(array:[Any]) -> [Int]{
    var temp = array
    temp.removeAll(where: {$0 is Int == false})
    return temp as! [Int]
}
  • Related