Assign values of an Int to two separate variables [duplicate] - ios

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])

Related

Function and array of strings using swift [duplicate]

This question already has answers here:
How to sort array of strings by length in reverse/descending order in Swift?
(2 answers)
Closed last year.
Good day everyone I want to create a function that takes an array of strings and return an array, sorted from shortest to longest but I'm getting a terminated by signal 4 error. I'm using an online swift compiler on my windows laptop if that somehow matters.
here's the code I wrote:
var siliconvalley = ["Google", "Apple", "Microsoft"]
var elementamount: Int = siliconvalley.count
var newarray: [String] = [] //new array created to store the newly sorted array
var a = siliconvalley[0].count // this variable was created to count the letters of the first string in the array
var temporary: String = "" // this was created to store the largest string so that I can use it to append the new array
func longestelement () -> [String] {
repeat {
if siliconvalley[1].count > a {
print (siliconvalley[1])
temporary = siliconvalley[1]
siliconvalley.remove(at:1)
}
else if siliconvalley[2].count > a {
print (siliconvalley[2])
temporary = siliconvalley[2]
siliconvalley.remove(at:2)
}
else {
print (siliconvalley[0])
temporary = siliconvalley[0]
siliconvalley.remove(at:0)
}
newarray.append(temporary)
elementamount = elementamount - 1
} while elementamount > 0
return newarray
}
print (longestelement())
You know swift has built-in sorting? You can do:
siliconvalley.sorted(by: {$0.count < $1.count})
and then if you just want the longest use .last
here's the issue:
while elementamount > 0
Consider rechecking the code for possible illogical loop termination condition.
P.S: elementamount is always greater than 0.

How to convert Array of Months Name to Months Number in swift [duplicate]

This question already has answers here:
How to find index of list item in Swift?
(23 answers)
Closed 4 years ago.
In my project, I am selecting months from picker view that month name is placed in Text field. But I have to send Month Number to the server.
This is my month array
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
Here I am getting a problem. For an example If I select April, I have to send 4 to the server, How to do this task please someone help/ advise me.
If you have the text value, just find the index of that value in the array and then add 1 (because the array is zero index based)
Something like this should work:
var monthsArray = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
if let index = monthsArray.index(of: "APRIL") { // index will be 3 (zero based)
let monthNumber = index + 1 // +1 as explained earlier
print(monthNumber) // output: 4
}
A function like this may help
func getMonthIndex(_ month: String) -> Int {
let months = ["JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"]
var monthIndex = -1
if let idx = months.index(of: month.uppercased()) {
monthIndex = idx + 1
}
return monthIndex
}
which can be used as follows :
var idx = getMonthIndex("January") //1
idx = getMonthIndex("JANUARY") //1
idx = getMonthIndex("DECEMBER") //12
idx = getMonthIndex("DECEMBERRRR") //-1
In the snipped above "month.uppercased()" is very important this will help to identify months in all cases such as "January", "JANUARY" OR "january"

Is there a way to capitalize letters randomly in a sentence in Swift? [duplicate]

This question already has an answer here:
How to randomize the case of letters in a string in Swift? [closed]
(1 answer)
Closed 6 years ago.
Just want a way to capitalize letters in a sentence randomly. Is it possible?
Try this,
var string: String = "your string"
var chars: [Any] = []
var letterIndexes: [Any] = []
for i in 0..<string.characters.count {
var ch: unichar = string[i]
// add each char as a string to a chars collection
chars.append("\(ch)")
// record the index of letters
if CharacterSet.letters.characterIsMember(ch) {
letterIndexes.append((i))
}
}
select randomly from the letterIndexes to determine which letters will be upper case. Convert the member of the chars array at that index to uppercase.
var charsToUppercase: Int = 12
var i = 0
while i < charsToUppercase && letterIndexes.count {
var randomLetterIndex: Int? = arc4random_uniform(((letterIndexes.count) as? u_int32_t))
var indexToUpdate = CInt(letterIndexes[randomLetterIndex])
letterIndexes.remove(at: randomLetterIndex)
chars[indexToUpdate] = chars[indexToUpdate].uppercased()
i += 1
}
ow all that's left is to join the chars array into a string.
var result: String = (chars as NSArray).componentsJoined(byString: "")
print("\(result)")
Refer this link for more information.

Converting a String to an Int Array [duplicate]

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]

How do you convert int to double in swift?

I've looked at the answers for converting int's to floats and other similar answers but they don't do exactly what I want.
I'm trying to create a basic program that takes a number does some different calculations onto it and the results of those calculations are added together at the end.
For one of those calculations I created a segmented controller with the 3 different values below
var myValues: [Double] = [0.00, 1.00, 1.50]
var myValue = [myValuesSegmentedController.selectedSegmentIndex]
then when one of those values is picked, it's added to the final value. All the values added together are Doubles to 2 decimal places.
var totalAmount = valueA + valueB + valueC + myValue
the problem I'm having is that swift won't let me add "myValue" to those final calculations. It gives me the error:
Swift Compiler Error. Cannot invoke '+' with an argument list of type '($T7, #lvalue [int])'
What do I need to do to change that value to a Double? Or what can I do to get a similar result?
You can cast it with Double() like this
var totalAmount = valueA + valueB + valueC + Double(myValue)
The problem is you are trying to add an array instead of an Int, so You don't even need to convert anything, considering that all of your values are already Doubles and your index actually has to be an Int. So
let myValues = [0.00, 1.00, 1.50]
let myValue = [myValuesSegmentedController.selectedSegmentIndex] // your mistake is here, you are creating one array of integers with only one element(your index)
The correct would be something like these:
let myValues = [0.00, 1.00, 1.50]
let totalAmount = myValues.reduce(0, combine: +) + myValues[myValuesSegmentedController.selectedSegmentIndex]
Put this in a playground:
var myValues: [Double] = [0.00, 1.00, 1.50]
let valueA = 1
let valueB = 2
let valueC = 3
var totalAmount = Double(valueA + valueB + valueC) + myValues[2]
println(totalAmount) //output is 7.5
valueA/B/C are all inferred to be Int.
totalAmount is inferred to be a Double
To convert a float to an integer in Swift. Basic casting like this does not work because these vars are not primitives, unlike floats and ints in Objective-C:
var float:Float = 2.2
var integer:Int = float as Float

Resources