How to put variable inside text field AND how to convert all elements to string NOT just 1 at a time? - ios

This is a follow up question to How to have 10 characters total and make sure at least one character from 4 different sets is used randomly
this is my code so far
let sets = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "1234567890", "\"-/:;()$&#.,?!'[]{}#%^\\|~<>€£¥•.,"].map { Array($0.characters) }
var randoms = sets.map { $0.random }
while randoms.count < 10 {
randoms.append(sets.random.random)
}
var convertedElems = String()
let something = randoms.shuffled()
for key in something {
convertedElems = String(key)
}
uniqueRoomID.text = randoms.shuffled()
Im getting an error saying cannot convert [Element] to type "String"
So i tried a for loop but that only converts 1 at a time when its supposed to do all 10
my other question is i tried storing a character in a variable and then setting a text field.text equal to that variable and nothing happened
What am i doing wrong here

Your randoms.shuffled() is an array of Characters. You need to convert it back into a String.
Change this:
uniqueRoomID.text = randoms.shuffled()
to this:
uniqueRoomID.text = String(randoms.shuffled())

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 do i fill up the Textbox input reminder bytes with ascii spaces in Swift 4?

Hi I am trying to use a UITextbox and restrict the number of characters input by the user to 10.
I have looked at using the below link,
Max length UITextField
My Questions,
1.Its not working as characters are depreciated in Swift 4 so the string.characters.count is throwing an error so what would be a workaround in Swift 4?
2.After the user enters his x number of characters, I want to make the reminders that is (limitlength - x) into empty spaces (ascii for space = 32 in decimal) so that reminder of the byte array is equal to dec 32.
I have tried doing this,
if let receivedData = rxCharacteristic?.value
let myByteArray = Array(receivedData) {
let b0 = myByteArray[0]
let b1 = myByteArray[1]
let b2 = myByteArray[2]
let b3 = myByteArray[3]
//Now reading data from textbox input
var userdata = textbox.text
let userdataarray: [UInt8] = Array(userdata!.utf8)
//I tried putting values into myByteArray as below
userdataarray[0] = myByteArray[0]
userdataarray[1] = myByteArray[1]
userdataarray[2] = myByteArray[2]
//The last value in myByteArray will remain unchanged so I'm not overwriting it
So from the question when I try to input textbox data less than its length its throwing an index out of range exception. But I went a little extreme to try the below code.
if(userdataarray[0] != 0 && userdataarray[0] != nil)
{
userdataarray[0] = myByteArray[0]
}
else
{
userdataarray[0] = 32 //Which is space in ascii
userdataarray[0] = myByteArray[0]
}
I don't think it worked but wanted to check on how its properly done?
If I understand your question correctly, then your trials are very much overenginering. In Swift you can just add characters to a String (as long as it is declared as var that is). This just boils down to
let orig = "Hello World"
var copy = orig
while copy.count < 15 {
copy.append(" ")
}
let dta = copy.data(using:.isoLatin1)!
let arr = Array(dta)
Since Swift is using some Unicode-encoding internally it is probably crucial to convert your String to data using a specific encoding if you plan to "directly" transfer it to some device that is limited to a certain character set. Still a lot less code than what you provided.

How to force iOS Speech API to read only numbers and recognize "one" as "1"

I want to use iOS Speech API to recognize mathematical expressions. It works okay for things like two plus four times three - reads it as 2+4*3, but when I start expression with 1 it always reads it as "One". When "One" is in the middle of expression it works as expected.
I figured out that when I set SFSpeechAudioBufferRecognitionRequest property taskHint to .search when displaying live results it recognizes 1 as "1" properly at first but at the end changes it to "One"
Is there a way to configure it to recognize only numbers?
Or just force to read "One" as "1" always?
Or the only way to fix it is to format result string on my own?
I have the same problem, but looks like there is no way to configure it.
I write this extension for my code, I'm checking every segment with this.
extension String {
var numericValue: NSNumber? {
//init number formater
let numberFormater = NumberFormatter()
//check if string is numeric
numberFormater.numberStyle = .decimal
guard let number = numberFormater.number(from: self.lowercased()) else {
//check if string is spelled number
numberFormater.numberStyle = .spellOut
//change language to spanish
//numberFormater.locale = Locale(identifier: "es")
return numberFormater.number(from: self.lowercased())
}
// return converted numeric value
return number
}
}
For example
{
let numString = "1.5"
let number = numString.numericValue //1.5
// or
let numString = "Seven"
let number = numString.numericValue //7
}

retrieving id and incrementing it swift3

I have a id whose format is 1223-3939-ABC.1 and I would like to retrieve the last value i.e. 1 and increment it so now it looks like 1223-3939-ABC.2. But its possible that "1" is not there so in that case, I would like to append ".1"
I am trying to achieve this in Swift and here is my code:
var deviceId: String = "1234-ASCD-SCSDS.1"
if (deviceId != "") {
var id: [String] = deviceId.components(separatedBy: ".")
if let incrementedId: String = id.capacity > 1 ? deviceId.components(separatedBy: ".")[1] : "" {
if (incrementedId == "") {
//should append to id
var firstEle = deviceId.components(separatedBy: ".")[0]
firstEle.append(".")
firstEle.append("1")
deviceId = firstEle
} else {
// retrieve that id, convert to int, increment id, convert back to string and replace the old id with new id
let newId: Int = Int(deviceId.components(separatedBy: ".")[1])! + 1
deviceId = deviceId.replacingOccurrences(of: ".\\d", with: ".\(newId)", options: .regularExpression)
}
}
}
Not sure what I'm doing wrong?
Your regular expression for replacing is .\\d where . is actually any symbol. Replace it with \\.\\d and it will operate as expected.
You are referencing capacity but you need to reference count to understand an amount of components.
Based on documentation:
Capacity – the total number of elements that the array can contain without
allocating new storage.
There are several problems, such as
Wrong usage of capacity (as already said by Nikita),
Your code assumes that there is only a single dot, so that id
has exactly two elements.
Your code will crash if the dot is not followed by an integer.
The main problem is that
deviceId = deviceId.replacingOccurrences(of: ".\\d", with: ".\(newId)", options: .regularExpression)
replaces all occurrences of an arbitrary character followed by
any digit with ".\(newId)". It should probably be
deviceId = id[0] + ".\(newId)"
instead.
But the entire problem can be solved much easier:
Find the last occurrence of a dot.
Check if the part of the string following the dot can be converted to an integer.
If yes, replace that part by the increased integer, otherwise append .1
Both checks can be achieved with conditional binding, so that the
if-block is only executed if the device id already has a trailing
number:
var deviceId = "1234-ASCD-SCSDS.1"
if let pos = deviceId.range(of: ".", options: .backwards),
let id = Int(deviceId.substring(from: pos.upperBound)) {
deviceId = deviceId.substring(to: pos.upperBound) + String(id + 1)
} else {
deviceId = deviceId + ".1"
}
print(deviceId) // 1234-ASCD-SCSDS.2

Converting string to int for check answer

For my math question app I have two random numbers generated then I have 4 buttons as answers. I want to check the answer if the user pushes the right button but it seems not to work.
num1 and num2 are the labels which the random numbers are generated in so technically
num1.text = "(randomnum1)"
and num2.text = "(randomnum2)" Thanks.
I have the following code under button1 IBaction
var sum = (num1) + (num2)
if btn1.titleLabel = (sum){
check.text = "right"
}
Maybe you should do some convert before you add num1 and num2. (convert strings to integers before adding them up, also, you should convert string to integer fisrt when comparing sum and btn.titleLabel)
you have two options:
if btn1.titleLabel.toInt()! == sum
or
if btn1.titleLabel == String(sum)
consider the difference between = (assign) and == (is equal)
to assign a number to a label use
num1.text = "\(randomnum1)"
I recommend to use backing Int variables like randomnum1 to hold the random numbers which can used for the math for example
var randomnum1 = 0, randomnum2 = 0 // instance variables of the class
randomnum1 = randomFuntion()
randomnum2 = randomFuntion()
num1.text = String(randomnum1)
num2.text = String(randomnum2)
now the labels contain the string values of the random numbers, but you can do the math with the associated variables.
var sum = randomnum1 + randomnum2
after that you can check the result as mentioned above
if btn1.titleLabel == String(sum) {
check.text = "right"
}

Resources