This question already has answers here:
Convert string array description to array
(5 answers)
Closed 6 years ago.
I've that type of String for example:
var test:String = "[1, 0, 4]";
And I need to convert it to an array of Int:
var testConverted:[Int] = [ 1, 0, 4 ];
You'll want to trim off the start and end brackets by using stringByTrimmingCharactersInSet, then get the array of string elements by using componentsSeparatedByString. Then you can finally use flatMap to create an array of integers from this.
For example:
let yourString = "[1, 0, 4]"
// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")
// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}
print(arrayOfInts)
Try this:
var test = "[1, 0, 4]"
test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]
Related
This question already has answers here:
How to split an Int to its individual digits?
(11 answers)
Closed 3 years ago.
say for example i have an Int var firstInt = 23 what i need is i want to assign the value of firstInt to two separate variables so the output would be var x = 2 and var y = 3. i tried converting the firstInt to a string like so var strFirstInt = String(firstInt) and wanted to assign the first index of the string to a different variable and the second index to another variable and convert them to Int but i couldn't pick the string by index. so any ideas how to do this?
You can use .compactMap from String like this :
let numberInt = 23
let digits = String(numberInt).compactMap{ $0.wholeNumberValue}
Response :
[2, 3]
And with this array, you put the first member to the first var and seconds to another:
var x = digits[0]
var y = digits[1]
print("The decade is \(x) and units is \(y)")
Response:
The decade is 2 and units is 3
Convert the firstInt to String and then to Array,
var firstInt = 23
let arr = Array(String(firstInt)).map({ String($0 )})
Next, get the elements as per the index from array, i.e.
var x = Int(arr[0])
var y = Int(arr[1])
Hi I would like to store values of a 1D array into a 2D array.
My 1D array has 50 elements and I want to store it in a 5x10 array, but whenever I do that, it always gives me a "Index out of range" error
Any help would be appreciated thanks!
var info2d = [[String]]()
var dataArray = outputdata.components(separatedBy: ";")
for j in 0...10 {
for i in 0...5 {
info2d[i][j] = dataArray[(j)*5+i]
print(info2d[i][j])
}
}
Lots of error in your code.
info2d must be initialised with default values before using it by index
// initialising 2d array with empty string value
var info2d = [[String]](repeating: [String](repeating: "", count: 10), count: 5)
Secondly for loop with ... includes the last value too, use ..<
for j in 0..<10 {
//...
}
Thirdly (j)*5+i is incorrect too.
Better Read how to use arrays, collections and for loop in swift.
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
I would make use of ArraySlice for this.
var arr2D = [[String]]()
for i in 0..<5 {
let start = i * 10
let end = start + 10
let slice = dataArray[start..<end] //Create an ArraySlice
arr2D.append(Array(slice)) //Create new Array from ArraySlice
}
This question already has answers here:
In Swift, Array [String] slicing return type doesn't seem to be [String]
(6 answers)
Closed 5 years ago.
While try to get sub array With given Range at that time this error.
Cannot subscript a value of type '[Info]' with an index of type 'CountableRange<Int>' .
My code is
Info Modal
class Info : NSObject {
var type : Type = .Unknown
var data = ""
init() {
super.init()
}
}
Array declaration
var currentData : [Info] = []
While trying this code
let moreAnimals: [Info] = self.currentData[0..<5] //above error disply.
let currentData = [Info(), Info(), Info()]
let subarr0 = currentData[0..<2] // ArraySlice<Info>
let subarr1 = Array(currentData[0..<2]) // Array<Info>
to fetch range of element from generics collection we need to convert to NSArray and fetch the element in range using subarrayWithRange Method.
var moreAnimals: [Int] = [1,2,3,4,5,6,7,8,9,10]
var otherarr: [Int] = (moreAnimals as NSArray).subarray(with: NSMakeRange(0, 5)) as! [Int]
output ::
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
This question already has answers here:
How to copy end of the Array in swift?
(6 answers)
Closed 6 years ago.
How can I remove the first n elements from an array of Int in Swift?
For example:
var array = [0, 1, 2, 3, 4, 5, 6]
let n = 4
The result array contains these elements:
[4, 5, 6]
let result = Array(array.dropFirst(n))
(Thanks to KPM and WolfLink for pointing out that let result = array.dropFirst(n) sets result to an ArraySlice which will not remain valid if the original array is released.)
Slightly more succinct than Mr. Johnson's answer:
let result = array.suffix(3)
I'd still go with his because dropFirst is more intuitive / readable than suffix.
You can use a range to slice the Array:
var array = [1,2,3,4,5,6]
let n = 4
print(array[n..<array.count]) //[4,5,6]
I have an Array which I have defined
var array: [Int] = Array(1...24)
I then add
array.insert(9999, atIndex: 0)
I would like to do something like
var array: [Int] = Array(9999...9999,1...24)
Is this possible ?
You could simply concatenate the arrays created from each range:
let array = Array(10 ... 14) + Array(1 ... 24)
Alternatively:
let array = [10 ... 14, 1 ... 4].flatMap { $0 }
which has the small advantage of not creating intermediate arrays
(as you can see in the open source implementation https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb).
As MartinR mentioned, you could simply concenate arrays using the + operator; and if this method is an answer for you, than this thread is a duplicate (see MartinR:s link), and should be closed.
If you explicitly wants to initialize an Int array using several ranges at once (see e.g. hola:s answer regarding array of ranges), you can make use of reduce as follows
let arr = [1...5, 11...15].reduce([]) { $0.0 + Array($0.1) }
Or, alternatively, flatten
var arr = Array([1...5, 11...15].flatten())
Both the above yields the following result
print(arr.dynamicType) // Array<Int>
print(arr) // [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
For an array of ranges you define the array as
let array: [Range<Int>] = [0...1, 5...100]
and so on and so forth.