How to check if a string is a character in Swift - swift

I have a textField (symbolTextField), I will input character to the textField. And only characters will be accepted in the textField. So I need to check if the input has a single character in the textField.
I have a button, I am updating the button state, when the symbolTextField has only one character instead of several characters (String), then the button will be enabled.
I am thinking about to add one more condition in the "saveButton.isEnabled = " to check if symbolTextField.text is a character, how can I do that?
func updateSaveButtonState() {
let symbolText = symbolTextField.text ?? ""
let nameText = nameTextField.text ?? ""
let descriptionText = descriptionTextField.text ?? ""
let usageText = usageTextField.text ?? ""
saveButton.isEnabled = !symbolText.isEmpty && !nameText.isEmpty && !descriptionText.isEmpty && !usageText.isEmpty
}

Assuming is a character means is one character just count the characters
By the way UITextField has a hasText property which reduces the code considerably.
func updateSaveButtonState() {
saveButton.isEnabled = nameTextField.hasText &&
descriptionText.hasText &&
usageTextField.hasText &&
symbolTextField.text!.count == 1
}

Related

MultiLine String can be null, how to hide it

I am using multiline string as follows. there is a line where I display submittedPerson, either can be his Id or email, but also can be nil as well. I wonder how do you hide this line if it returns nil
var submittedPerson = ""
if let Id = User[index].Id {
submittedPerson = Id
} else if let email = User[index].email {
submittedPerson = email
}
let displayStr = """
\(department)
\"submittedBy" : \(submittedPerson)
\(submittedDate)
"""
I'll assume the hidden requirement here is that you still want to keep the multiline string literal readable, and not have code duplication :)
One way you could do this is to move one of the two line feed characters to when you assign to submittedPerson:
var submittedPerson: String? = ""
if let Id = User[index].Id {
submittedPerson = "\n\(Id)\n" // note the lines feeds
} else if let email = User[index].email {
submittedPerson = "\n\(email)\n"
}
let displayStr = """
\(department)
\(submittedPerson ?? "")
\(submittedDate)
"""

I want to delete last integers value swift

I want to delete only integer value from any string. Is it possible or not?
let string = "kjgd5676idbh123456"
i want to result this string = kjgd5676idbh
I want to delete only the last integer value. How to remove the last integer value?
If you would like to delete the whole value 123456 you can use regex \\d+ to match any number with 1 digit or more and anchor it to the end of the string using the dolar sign $
let str = "kjgd5676idbh123456"
if let index = str.range(of: "\\d+$", options: .regularExpression)?.lowerBound {
print("Last Number:", str[index...]) // 123456
print("Prefix:", str[..<index]) // kjgd5676idbh
}
If you need to remove a single digit suffix you just need to remove the plus sign of your regex. "\\d$"
Search backwards for the first non-digit character and drop the trailing digits
let string = "kjgd5676idbh123456"
let result : String
if let range = string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted, options: .backwards) {
result = String(string[..<range.upperBound])
} else {
result = Int(string) == nil ? string : ""
}

Form validation issue in macOS app

I am trying to run through a settings form and make sure that the user hasn't left any of the required fields empty.
Some of the forms fields are secure ( eg password).
Whats the easiest way to loop through all these fields and check they are not empty?
I have tried below - but I get a weird error:
if textfield1.stringValue == "",
textfield2.stringValue == "",
passwordfield.stringValue == "" {
//Shows error: Braced block of statements is an unused closure
}
Additionally I am unable to group all these NSTextfields into an array as the password textfields are NSSecureTextField which despite being inherited from NSTextfield, the are not groupable with NSTextfield.
You can have NSTextField and NSSecureTextField in the same array. This is indeed an easy way to find the empty ones.
let tf = NSTextField()
let stf = NSSecureTextField()
let tf2 = NSTextField()
tf2.stringValue = "some text"
let all = [tf, stf, tf2]
let emptyTextFields = all.filter { $0.stringValue.isEmpty }
Also in your example you can't use commas to group conditions in if, you have to use &&:
if tf.stringValue.isEmpty && stf.stringValue.isEmpty && tf2.stringValue.isEmpty {
// do something
}
but this is not a good solution, better use the array and filter.
Under Swift 2, here's what Eric Aya correctly identified:
if textfield1.stringValue == "" && textfield2.stringValue == "" && == "" {
}
It also compiles under Swift 3.
On the other hand, the code you put in your question actually works in Swift 3.
Other way to check empty string with isEmpty variable of String object.
let userName = ""
let email = ""
if(userName.isEmpty && email.isEmpty) {
print("empty strings")
}
else {
print("good strings")
}

In swift how do I see if a specific character is present in a UITextField?

Firstly, apologies - new to all this.
I am trying to take whatever text a user has inputted to a UITextField and see if it contains a certain letter, then count the number of times that letter has been entered.
So for example, if the string was "Hello" I would want it to return, as a score if like, that there are two l's. I don't want it to be case sensitive.
Thanks!
You can use try this extension:
extension String
{
func numberOfChars(char:Character) -> Int
{
var counter = 0
for chr in self
{
if chr == char
{
counter++
}
}
return counter
}
}
And then use it like:
println(textField.text.numberOfChars(Character("a")))
To check when the user has entered text in your UITextField you can use: addObserver to the UITextField and create a method using observeValueForKeyPath. In this method you can use to count the number of characters:
let someString = "Hello"
let count = Array(someString).map { $0 == "l" }.filter { $0 == true }.count
To use an extension like Dejan Skledar suggested:
extension String {
func numberOfChars(char: Character) -> Int {
return Array(someString).map { $0 == "l" }.filter { $0 == true }.count
}
}
and use it like:
println(textField.text.numberOfChars("l") // prints "3"

Arabic text stripper / parser

I'm new to programming. I made a function that removes the vowels on Arabic text input. My question is if I used the best loop for the task or is there a better and more concise way to write this?
It would be nice to improve the code. Thank you.
// It seems to work now. I solved it.
// What do you think? :) Happy that I managed to solve it.
// Programming is fun!!! :D
var arabic:String = "الْعَرَبِيَّةُ لُغَةٌ جَمِيلَةٌ"
func txtStripper(arabic: String) -> String {
var strippedTxt = ""
for character in arabic {
if character != "َ" && character != "ِ" && character != "ّ" && character != "ْ" && character != "ُ" && character != "ٌ" && character != "ً" && character != "ٍ" {
strippedTxt += toString(print(character))
}
}
return strippedTxt
}
txtStripper(arabic)
First of all you can clean up the if statement by using contains function.
func txtStripper(arabic: String) -> String {
var strippedTxt = ""
let vowels : Character[] = ["َ", "ِ", "ّ", "ْ", "ُ", "ٌ", "ً", "ٍ"]
for character in arabic {
if !contains (vowels, character) {
strippedTxt += toString(character)
}
}
return strippedTxt
}
Next, if you are comfortable with closures, you can rewrite the whole function in much more concise way as follows:
func txtStripperWithClosures(arabic:String) -> String {
let vowels : Character[] = ["َ", "ِ", "ّ", "ْ", "ُ", "ٌ", "ً", "ٍ"]
return Array(arabic).filter({!contains(vowels, $0)}).reduce("",+)
}
It works as follows:
Array(arabic) turns the String into Character[]
filter({!contains(vowels, $0)}) removes the vowel characters from the array
reduce("",+) joins the character list back into a String