concatenating NSString and Int in Apple Swift - ios

I have used arc4random_uniform() to get the random values from given String or Int. Now I want to join those to values.
var randomNumber = arc4random_uniform(9999) + 1000 // returns random number between 1000 and 9999 e.g. - 7501
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
What I want is to display 7501 and E together like 7501E
var str="\(randomNumber)\(random_alphabet)" // error
I am getting below error :
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
Please help how can I display this together.

It works fine with the right punctuation:
var randomNumber = arc4random_uniform(999) + 1000
// returns random number between 1000 and 9999 e.g. - 7501 NOTE 999 not 9999
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
// Note missing "=" in OP
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
var str = "\(randomNumber)\(random_alphabet)" // e.g. 1197A

Instead of using string interpolation, you could also convert the random number to a string and just add them together:
let str = randomNumber.description + random_alphabet

Related

How to convert sequence of ASCII code into string in swift 4?

I have an sequence of ASCII codes in string format like (7297112112121326610511411610410097121). How to convert this into text format.
I tried below code :
func convertAscii(asciiStr: String) {
var asciiString = ""
for asciiChar in asciiStr {
if let number = UInt8(asciiChar, radix: 2) { // Cannot invoke initializer for type 'UInt8' with an argument list of type '(Character, radix: Int)'
print(number)
let character = String(describing: UnicodeScalar(number))
asciiString.append(character)
}
}
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
But getting error in if let number line.
As already mentioned decimal ASCII values are in range of 0-255 and can be more than 2 digits
Based on Sulthan's answer and assuming there are no characters < 32 (0x20) and > 199 (0xc7) in the text this approach checks the first character of the cropped string. If it's "1" the character is represented by 3 digits otherwise 2.
func convertAscii(asciiStr: String) {
var source = asciiStr
var result = ""
while source.count >= 2 {
let digitsPerCharacter = source.hasPrefix("1") ? 3 : 2
let charBytes = source.prefix(digitsPerCharacter)
source = String(source.dropFirst(digitsPerCharacter))
let number = Int(charBytes)!
let character = UnicodeScalar(number)!
result += String(character)
}
print(result) // "Happy Birthday"
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
If we consider the string to be composed of characters where every character is represented by 2 decimal letters, then something like this would work (this is just an example, not optimal).
func convertAscii(asciiStr: String) {
var source = asciiStr
var characters: [String] = []
let digitsPerCharacter = 2
while source.count >= digitsPerCharacter {
let charBytes = source.prefix(digitsPerCharacter)
source = String(source.dropFirst(digitsPerCharacter))
let number = Int(charBytes, radix: 10)!
let character = UnicodeScalar(number)!
characters.append(String(character))
}
let result: String = characters.joined()
print(result)
}
convertAscii(asciiStr: "7297112112121326610511411610410097121")
However, the format itself is ambigious because ASCII characters can take from 1 to 3 decimal digits, therefore to parse correctly, you need all characters to have the same length (e.g. 1 should be 001).
Note that I am taking always the same number of letters, then convert them to a number and then create a character the number.

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.

Random Password Generator Swift 3?

I'm building a random password generator for iOS. In it, a button generates a random password that has characteristics chosen by the user (e.g. switches to turn on or off lowercase and uppercase letters, characters and symbols, and so on).
The UI looks great, the rest of the code is working smoothly, but I can't get my button to actually generate a random alphanumerical string. I have a label with some placeholder text ("Your Password") that should have its text updated to a random string when the button is pushed, but I am getting a compiler error: "unresolved use of identifier 'length'"
Here is the current code for the button:
#IBAction func generatePassword(_ sender: UIButton) {
let randomPasswordArray: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let len = UInt32(randomPasswordArray.length)
var randomPassword = ""
for _ in 0 ..< length {
let rand = arc4random(len)
var nextChar = randomPasswordArray.character(at: Int(rand))
randomPassword += NSString(characters: &nextChar, length: 1) as String
}
passwordLabel.text = "randomPassword"
}
Thanks!
First create an array with your password allowed characters
let passwordCharacters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".characters)
then choose the password lenght
let len = 8
define and empty string password
var password = ""
create a loop to gennerate your random characters
for _ in 0..<len {
// generate a random index based on your array of characters count
let rand = arc4random_uniform(UInt32(passwordCharacters.count))
// append the random character to your string
password.append(passwordCharacters[Int(rand)])
}
print(password) // "V3VPk5LE"
Swift 4
You can also use map instead of a standard loop:
let pswdChars = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
let rndPswd = String((0..<len).map{ _ in pswdChars[Int(arc4random_uniform(UInt32(pswdChars.count)))]})
print(rndPswd) // "oLS1w3bK\n"
Swift 4.2
Using the new Collection's randomElement() method:
let len = 8
let pswdChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let rndPswd = String((0..<len).compactMap{ _ in pswdChars.randomElement() })
print(rndPswd) // "3NRQHoiA\n"
You can also use
import Security
let password = SecCreateSharedWebCredentialPassword() as String?
print(password)
Your code should be
...
for _ in 0 ..< len {
...

How to generate a 4 digit random number with unique digits?

Like: 0123, 0913, 7612
Not like: 0000, 1333, 3499
Can it be done with arcRandom() in swift? Without array or loop?
Or If that impossible, how it be done with arcRandom() in any way ?
You just want to shuffle the digits and pick the number you want.
Start with Nate Cook's Fischer-Yates shuffle code.
// Start with the digits
let digits = 0...9
// Shuffle them
let shuffledDigits = digits.shuffle()
// Take the number of digits you would like
let fourDigits = shuffledDigits.prefix(4)
// Add them up with place values
let value = fourDigits.reduce(0) {
$0*10 + $1
}
var fourUniqueDigits: String {
var result = ""
repeat {
// create a string with up to 4 leading zeros with a random number 0...9999
result = String(format:"%04d", arc4random_uniform(10000) )
// generate another random number if the set of characters count is less than four
} while Set<Character>(result.characters).count < 4
return result // ran 5 times
}
fourUniqueDigits // "3501"
fourUniqueDigits // "8095"
fourUniqueDigits // "9054"
fourUniqueDigits // "4728"
fourUniqueDigits // "0856"
Swift Code - For Generation of 4 digit
It gives number between 1000 and 9999.
func random() -> String {
var result = ""
repeat {
result = String(format:"%04d", arc4random_uniform(10000) )
} while result.count < 4 || Int(result)! < 1000
print(result)
return result
}
Please Note - You can remove this Int(result)! < 1000 if you want numbers like this - 0123, 0913

How do you use parse string in swift?

An issue here to me that if i use parse string for the result of calculator program for instance,
4.5 * 5.0 = 22.5
how can I use splitting here to depart decimal part from result?
Assuming you're working with strings only :
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
Use modf to extract decimal part from result.
Objective-C :
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(#"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
Want only interger part from double of float
Want only integer value from double then
let integerValue:Int = Int(integral)
println(integerValue)
Want only integer value from float then
let integerValue:Float = Float(integral)
println(integerValue)

Resources