Swift beginner Error - swift

The original question was "The function beginsWithVowel should take a single String parameter and return a Bool indicating whether the input string begins with a vowel. If the input string begins with a vowel return true, otherwise return false."
func lowercase(a: String) ->String{
return a.lowercaseString
}
func lowercase(a: String) ->String{
return a.lowercaseString
}
func beginsWithVowel(a: String) ->Bool {
if a.characters[a.startIndex] != ("a") && a.characters[a.startIndex] != ("e") && a.characters[a.startIndex] != ("i") && a.characters[a.startIndex] != ("o") && a.characters[a.startIndex] != ("u") {
print("The word must start with a vowel letter.")
return false
}else {
print("Succes!")
return true
}
}
When the a = ""
beginsWithVowel(lowercase(""))
An error occurred.
What should I add to make the function say reminder sentence instead of an error?
I have tried to add those into my code, but the error still occurred(ps: the func lowercase was added after fails)
a.characters[a.startIndex] != ("")
and
if a.characters.count == 0 {
}

You can simply return false if your string is empty otherwise create a string with the vowels and check if it contains the first character of your string:
Swift 3
func beginsWithVowel(a: String) -> Bool {
return a.isEmpty ? false : "aeiouAEIOU".characters.contains(a.characters.first!)
}
Swift 4
func beginsWithVowel(a: String) ->Bool {
return a.isEmpty ? false : "aeiouAEIOU".contains(a.first!)
}
beginsWithVowel(a: "Apple") // true
Note that it will return false for vowels with accent. If you would like to make your method diacritic insensitive you can use string's method func folding(options: String.CompareOptions = default, locale: Locale?) -> String to return the string without accent for comparison:
Swift 3
func beginsWithVowel(a: String) ->Bool {
return a.isEmpty ? false : "aeiouAEIOU".characters.contains(a.folding(options: .diacriticInsensitive, locale: nil).characters.first!)
}
Swift 4
func beginsWithVowel(a: String) ->Bool {
return a.isEmpty ? false : "aeiouAEIOU".contains(a.folding(options: .diacriticInsensitive, locale: nil).first!)
}
beginsWithVowel(a: "águia") // true

Related

Fixing character count, decimal count, and "0" character count in swift

When I run this code, I can only insert the "." once. If it is already in one of the text fields I can't use another "." in another text field, this is the same with the character count. If 8 characters are entered in one text field no characters can be entered in any of the other text fields.
func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
// cost of materials
if (costOfMaterialsTXT.text?.contains("."))! && string == "." {
return false
}
// tech hours
if (techHoursTXT.text?.contains("."))! && string == "." {
return false
}
// helper hours
if (helperHoursTXT.text?.contains("."))! && string == "." {
return false
}
//Prevent "0" characters as the first characters
// cost of materials
if (costOfMaterialsTXT.text == "0" && string.isEmpty) {
return true
} else if (costOfMaterialsTXT.text == "0" && string != ".") {
return false
}
// tech hours
if (techHoursTXT.text == "0" && string.isEmpty) {
return true
} else if (techHoursTXT.text == "0" && string != ".") {
return false
}
// helper hours
if (helperHoursTXT.text == "0" && string.isEmpty) {
return true
} else if (helperHoursTXT.text == "0" && string != ".") {
return false
}
//Limit the character count to 8
// cost of materials
if ((costOfMaterialsTXT.text!) + string).count > 8 {
return false
}
// tech hours
if ((techHoursTXT.text!) + string).count > 8 {
return false
}
// helper hours
if ((helperHoursTXT.text!) + string).count > 8 {
return false
}
// Only Numbers And Decimal-Point Allowed
let allowedCharacters = "0123456789."
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharactersSet = CharacterSet(charactersIn: string)
return allowedCharacterSet.isSuperset(of: typedCharactersSet)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
guard [costOfMaterialsTXT, techHoursTXT, helperHoursTXT].contains(textField) else {
return true //It's another textfield, is it even possible? Do you have more textField?
}
if (textField.text?.contains("."))! && string == "." {
return false
}
//Prevent "0" characters as the first characters
if (textField.text == "0" && string.isEmpty) {
return true
} else if (textField.text == "0" && string != ".") {
return false
}
//Limit the character count to 8
if ((textField.text!) + string).count > 8 {
return false
}
let allowedCharacters = "0123456789."
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharactersSet = CharacterSet(charactersIn: string)
return allowedCharacterSet.isSuperset(of: typedCharactersSet)
}
Here's the minima factorization.
You check at start if it's one of your UITextField with that behavior. Read the textField parameter.
You do the SAME behavior for each UITextField, so you shouldn't care about costOfMaterialsTXT, techHoursTXT, nor helperHoursTXT, it's any of these UITextField.
Now, about the code in itself...
You can remove the guard at the beginning if you only have those 3.
You should unwrap correctly here textField.text?.contains("."))! and textField.text!. What if string is "./.." (from a copy/paste) for instance?

check string is int or double , with extension in swift 3

I have string extension you can see under below but only returns true for Int , I want to return it true, for All , Int and Double values only.
extension String {
var isnumberordouble : Bool {
get{
return self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
}
How can I fix it ? Any idea ? ty.
As #MartinR said, check if the string can be converted to an Int or a Double:
extension String {
var isnumberordouble: Bool { return Int(self) != nil || Double(self) != nil }
}
print("1".isnumberordouble) // true
print("1.2.3".isnumberordouble) // false
print("1.2".isnumberordouble) // true
#MartinR raises a good point in the comments. Any value that converts to an Int would also convert to a Double, so just checking for conversion to Double is sufficient:
extension String {
var isnumberordouble: Bool { return Double(self) != nil }
}
Handling leading and trailing whitespace
The solution above works, but it isn't very forgiving if your String has leading or trailing whitespace. To handle that use the trimmingCharacters(in:) method of String to remove the whitespace (requires Foundation):
import Foundation
extension String {
var isnumberordouble: Bool { return Double(self.trimmingCharacters(in: .whitespaces)) != nil }
}
print(" 12 ".isnumberordouble) // true

How to check for palindrome in Swift using recursive definition

I like many of the features in Swift, but using manipulating strings are still a big pain in the ass.
func checkPalindrome(word: String) -> Bool {
print(word)
if word == "" {
return true
} else {
if word.characters.first == word.characters.last {
return checkPalindrome(word.substringWithRange(word.startIndex.successor() ..< word.endIndex.predecessor()))
} else {
return false
}
}
}
This code fails miserably whenever the string's length is an odd number. Of course I could make it so the first line of the block would be if word.characters.count < 2, but is there a way in Swift to get substrings and check easily?
Update
I like many of the suggestions, but I guess the original question could be misleading a little, since it's a question about String more than getting the right results for the function.
For instance, in Python, checkPalindrome(word[1:-1]) would work fine for the recursive definition, whereas Swift code is much less graceful since it needs other bells and whistles.
return word == String(word.reversed())
func isPalindrome(myString:String) -> Bool {
let reverseString = String(myString.characters.reversed())
if(myString != "" && myString == reverseString) {
return true
} else {
return false
}
}
print(isPalindrome("madam"))
I have used the below extension to find whether the number is Palindrome or Not.
extension String {
var isPalindrome: Bool {
return self == String(self.reversed())
}
}
Sometimes having a front end for a recursion can simplify life. I sometimes do this when the arguments which are most convenient to use are not what I want in the user interface.
Would the following meet your needs?
func checkPalindrome(str: String) -> Bool {
func recursiveTest(var charSet: String.CharacterView) -> Bool {
if charSet.count < 2 {
return true
} else {
if charSet.popFirst() != charSet.popLast() {
return false
} else {
return recursiveTest(charSet)
}
}
}
return recursiveTest(str.characters)
}
just add on more condition in if
func checkPalindrome(word: String) -> Bool {
print(word)
if (word == "" || word.characters.count == 1){
return true
}
else {
if word.characters.first == word.characters.last {
return checkPalindrome(word.substringWithRange(word.startIndex.successor() ..< word.endIndex.predecessor()))
} else {
return false
}
}
}
extension StringProtocol where Self: RangeReplaceableCollection {
var letters: Self { filter(\.isLetter) }
var isPalindrome: Bool {
let letters = self.letters
return String(letters.reversed()).caseInsensitiveCompare(letters) == .orderedSame
}
}
"Dammit I'm Mad".isPalindrome // true
"Socorram-me subi no onibus em marrocos".isPalindrome // true
You can also break your string into an array of characters and iterate through them until its half comparing one by one with its counterpart:
func checkPalindrome(_ word: String) -> Bool {
let chars = Array(word.letters.lowercased())
for index in 0..<chars.count/2 {
if chars[index] != chars[chars.count - 1 - index] {
return false
}
}
return true
}
And the recursive version fixing the range issue where can't form a range with endIndex < startIndex:
func checkPalindrome<T: StringProtocol>(_ word: T) -> Bool {
let word = word.lowercased()
.components(separatedBy: .punctuationCharacters).joined()
.components(separatedBy: .whitespacesAndNewlines).joined()
if word == "" || word.count == 1 {
return true
} else {
if word.first == word.last {
let start = word.index(word.startIndex,offsetBy: 1, limitedBy: word.endIndex) ?? word.startIndex
let end = word.index(word.endIndex,offsetBy: -1, limitedBy: word.startIndex) ?? word.endIndex
return checkPalindrome(word[start..<end])
} else {
return false
}
}
}
checkPalindrome("Dammit I'm Mad")
I think if you make an extension to String like this one then it will make your life easier:
extension String {
var length: Int { return characters.count }
subscript(index: Int) -> Character {
return self[startIndex.advancedBy(index)]
}
subscript(range: Range<Int>) -> String {
return self[Range<Index>(start: startIndex.advancedBy(range.startIndex), end: startIndex.advancedBy(range.endIndex))]
}
}
With it in place, you can change your function to this:
func checkPalindrome(word: String) -> Bool {
if word.length < 2 {
return true
}
if word.characters.first != word.characters.last {
return false
}
return checkPalindrome(word[1..<word.length - 1])
}
Quick test:
print(checkPalindrome("aba")) // Prints "true"
print(checkPalindrome("abc")) // Prints "false"
extension String {
func trimmingFirstAndLastCharacters() -> String {
guard let startIndex = index(self.startIndex, offsetBy: 1, limitedBy: self.endIndex) else {
return self
}
guard let endIndex = index(self.endIndex, offsetBy: -1, limitedBy: self.startIndex) else {
return self
}
guard endIndex >= startIndex else {
return self
}
return String(self[startIndex..<endIndex])
}
var isPalindrome: Bool {
guard count > 1 else {
return true
}
return first == last && trimmingFirstAndLastCharacters().isPalindrome
}
}
We first declare a function that removes first and last characters from a string.
Next we declare a computer property which will contain the actual recursive code that checks if a string is palindrome.
If string's size is less than or equal 1 we immediately return true (strings composed by one character like "a" or the empty string "" are considered palindrome), otherwise we check if first and last characters of the string are the same and we recursively call isPalindrome on the current string deprived of the first and last characters.
Convert the string into an Array. When the loop is executed get the first index and compare with the last index.
func palindrome(string: String)-> Bool{
let char = Array(string)
for i in 0..<char.count / 2 {
if char[i] != char[char.count - 1 - i] {
return false
}
}
return true
}
This solution is not recursive, but it is a O(n) pure index based solution without filtering anything and without creating new objects. Non-letter characters are ignored as well.
It uses two indexes and walks outside in from both sides.
I admit that the extension type and property name is stolen from Leo, I apologize. 😉
extension StringProtocol where Self: RangeReplaceableCollection {
var isPalindrome : Bool {
if isEmpty { return false }
if index(after: startIndex) == endIndex { return true }
var forward = startIndex
var backward = endIndex
while forward < backward {
repeat { formIndex(before: &backward) } while !self[backward].isLetter
if self[forward].lowercased() != self[backward].lowercased() { return false }
repeat { formIndex(after: &forward) } while !self[forward].isLetter
}
return true
}
}
Wasn't really thinking of this, but I think I came up with a pretty cool extension, and thought I'd share.
extension String {
var subString: (Int?) -> (Int?) -> String {
return { (start) in
{ (end) in
let startIndex = start ?? 0 < 0 ? self.endIndex.advancedBy(start!) : self.startIndex.advancedBy(start ?? 0)
let endIndex = end ?? self.characters.count < 0 ? self.endIndex.advancedBy(end!) : self.startIndex.advancedBy(end ?? self.characters.count)
return startIndex > endIndex ? "" : self.substringWithRange(startIndex ..< endIndex)
}
}
}
}
let test = ["Eye", "Pop", "Noon", "Level", "Radar", "Kayak", "Rotator", "Redivider", "Detartrated", "Tattarrattat", "Aibohphobia", "Eve", "Bob", "Otto", "Anna", "Hannah", "Evil olive", "Mirror rim", "Stack cats", "Doom mood", "Rise to vote sir", "Step on no pets", "Never odd or even", "A nut for a jar of tuna", "No lemon, no melon", "Some men interpret nine memos", "Gateman sees name, garageman sees nametag"]
func checkPalindrome(word: String) -> Bool {
if word.isEmpty { return true }
else {
if word.subString(nil)(1) == word.subString(-1)(nil) {
return checkPalindrome(word.subString(1)(-1))
} else {
return false
}
}
}
for item in test.map({ $0.lowercaseString.stringByReplacingOccurrencesOfString(",", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "") }) {
if !checkPalindrome(item) {
print(item)
}
}
A simple solution in Swift:
func isPalindrome(word: String) -> Bool {
// If no string found, return false
if word.count == 0 { return false }
var index = 0
var characters = Array(word) // make array of characters
while index < characters.count / 2 { // repeat loop only for half length of given string
if characters[index] != characters[(characters.count - 1) - index] {
return false
}
index += 1
}
return true
}
func checkPalindrome(_ inputString: String) -> Bool {
if inputString.count % 2 == 0 {
return false
} else if inputString.count == 1 {
return true
} else {
var stringCount = inputString.count
while stringCount != 1 {
if inputString.first == inputString.last {
stringCount -= 2
} else {
continue
}
}
if stringCount == 1 {
return true
} else {
return false
}
}
}

Swift: Iterating through String when I receive a “fatal error: unexpectedly found nil while unwrapping an Optional value”

I'm currently making a Decimal to Binary calculator in SWIFT and have run into this error while iterating through a string. My calculator only works if a decimal is included currently so I've been trying to fix that using the .rangeOfString Operator . The error ONLY occurs when I give the function a number without a decimal - in this case 31
import UIKit
var Input : String = "31";
func Splitter(UserInput : String) -> (Interger: Int, Decimal: Double, DecimalLength : Int)
{
var DecimalPortion : String = ""
var IntergerPortion : String = ""
var AfterDecimal : Bool = false
var DecimalLength : Int
var HasDecimal : Bool
if UserInput.rangeOfString(".") != nil
{
**for character in UserInput** //error is thrown here.
{
if AfterDecimal == true
{
DecimalPortion += String(character)
}
if character == "."
{
AfterDecimal = true
}
}
Swift deals correctly with Unicode strings and string indices are not what you think they are. Additionally the rangeOfString() function returns a range which you don't seem to be using effectively. Here is another approach:
func splitter (input : String) -> (String?, String?) {
let split = input.componentsSeparatedByString (".")
switch split.count {
case 1: return (split[0], nil)
case 2: return ((split[0].isEmpty ? nil : split[0]),
(split[1].isEmpty ? nil : split[1]))
default: return (nil, nil)
}
}
15> splitter("12.34")
$R5: (String?, String?) = { 0 = "12", 1 = "34" }
16> splitter("12")
$R6: (String?, String?) = { 0 = "12", 1 = nil }
17> splitter("12.")
$R7: (String?, String?) = { 0 = "12", 1 = nil }
18> splitter(".12")
$R9: (String?, String?) = { 0 = nil, 1 = "12" }
i don't know what is the wrong but i tried this
var characters = Array(UserInput)
for value in characters
{
println(value);
if AfterDecimal == true
{
DecimalPortion += String(value)
}
if value == "."
{
AfterDecimal = true
}
}

How to check is a string or number?

I have an array ["abc", "94761178","790"]
I want to iterate each and check is a String or an Int?
How to check it?
How to convert "123" to integer 123?
Here is a small Swift version using String extension :
Swift 3/Swift 4 :
extension String {
var isNumber: Bool {
return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
Swift 2 :
extension String {
var isNumber : Bool {
get{
return !self.isEmpty && self.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) == nil
}
}
}
Edit Swift 2.2:
In swift 2.2 use Int(yourArray[1])
var yourArray = ["abc", "94761178","790"]
var num = Int(yourArray[1])
if num != nil {
println("Valid Integer")
}
else {
println("Not Valid Integer")
}
It will show you that string is valid integer and num contains valid Int.You can do your calculation with num.
From docs:
If the string represents an integer that fits into an Int, returns the
corresponding integer.This accepts strings that match the regular
expression "[-+]?[0-9]+" only.
Be aware that checking a string/number using the Int initializer has limits. Specifically, a max value of 2^32-1 or 4294967295. This can lead to problems, as a phone number of 8005551234 will fail the Int(8005551234) check despite being a valid number.
A much safer approach is to use NSCharacterSet to check for any characters matching the decimal set in the range of the string.
let number = "8005551234"
let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
if !number.isEmpty && number.rangeOfCharacterFromSet(numberCharacters) == nil {
// string is a valid number
} else {
// string contained non-digit characters
}
Additionally, it could be useful to add this to a String extension.
public extension String {
func isNumber() -> Bool {
let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
return !self.isEmpty && self.rangeOfCharacterFromSet(numberCharacters) == nil
}
}
I think the nicest solution is:
extension String {
var isNumeric : Bool {
return Double(self) != nil
}
}
Starting from Swift 2, String.toInt() was removed.
A new Int Initializer was being introduced: Int(str: String)
for target in ["abc", "94761178","790"]
{
if let number = Int(target)
{
print("value: \(target) is a valid number. add one to get :\(number+1)!")
}
else
{
print("value: \(target) is not a valid number.")
}
}
Swift 3, 4
extension String {
var isNumber: Bool {
let characters = CharacterSet.decimalDigits.inverted
return !self.isEmpty && rangeOfCharacter(from: characters) == nil
}
}
Simple solution like this:
extension String {
public var isNumber: Bool {
return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
I think using NumberFormatter is an easy way:
(Swift 5)
import Foundation
extension String {
private static let numberFormatter = NumberFormatter()
var isNumeric : Bool {
Self.numberFormatter.number(from: self) != nil
}
}
The correct way is to use the toInt() method of String, and an optional binding to determine whether the conversion succeeded or not. So your loop would look like:
let myArray = ["abc", "94761178","790"]
for val in myArray {
if let intValue = val.toInt() {
// It's an int
println(intValue)
} else {
// It's not an int
println(val)
}
}
The toInt() method returns an Int?, so an optional Int, which is nil if the string cannot be converted ton an integer, or an Int value (wrapped in the optional) if the conversion succeeds.
The method documentation (shown using CMD+click on toInt in Xcode) says:
If the string represents an integer that fits into an Int, returns the corresponding integer. This accepts strings that match the regular expression "[-+]?[0-9]+" only.
This way works also with strings with mixed numbers:
public extension String {
func isNumber() -> Bool {
return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil && self.rangeOfCharacter(from: CharacterSet.letters) == nil
}}
So u get something like this:
Swift 3.0 version
func isNumber(stringToTest : String) -> Bool {
let numberCharacters = CharacterSet.decimalDigits.inverted
return !s.isEmpty && s.rangeOfCharacter(from:numberCharacters) == nil
}
If you want to accept a more fine-grained approach (i.e. accept a number like 4.5 or 3e10), you proceed like this:
func isNumber(val: String) -> Bool
{
var result: Bool = false
let parseDotComNumberCharacterSet = NSMutableCharacterSet.decimalDigitCharacterSet()
parseDotComNumberCharacterSet.formUnionWithCharacterSet(NSCharacterSet(charactersInString: ".e"))
let noNumberCharacters = parseDotComNumberCharacterSet.invertedSet
if let v = val
{
result = !v.isEmpty && v.rangeOfCharacterFromSet(noNumberCharacters) == nil
}
return result
}
For even better resolution, you might draw on regular expression..
Xcode 8 and Swift 3.0
We can also check :
//MARK: - NUMERIC DIGITS
class func isString10Digits(ten_digits: String) -> Bool{
if !ten_digits.isEmpty {
let numberCharacters = NSCharacterSet.decimalDigits.inverted
return !ten_digits.isEmpty && ten_digits.rangeOfCharacter(from: numberCharacters) == nil
}
return false
}
This code works for me for Swift 3/4
func isNumber(textField: UITextField) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: textField.text!)
return allowedCharacters.isSuperset(of: characterSet)
// return true
}
You can use this for integers of any length.
func getIntegerStrings(from givenStrings: [String]) -> [String]
{
var integerStrings = [String]()
for string in givenStrings
{
let isValidInteger = isInteger(givenString: string)
if isValidInteger { integerStrings.append(string) }
}
return integerStrings
}
func isInteger(givenString: String) -> Bool
{
var answer = true
givenString.forEach { answer = ("0"..."9").contains($0) && answer }
return answer
}
func getIntegers(from integerStrings: [String]) -> [Int]
{
let integers = integerStrings.compactMap { Int($0) }
return integers
}
let strings = ["abc", "94761178", "790", "18446744073709551615000000"]
let integerStrings = getIntegerStrings(from: strings)
let integers = getIntegers(from: integerStrings)
print(integerStrings) // ["94761178", "790", "18446744073709551615000000"]
print(integers) // [94761178, 790]
However, as pointed out by #Can, you can get the integer value for the number only up to 2^31 - 1 (signed integer limit on 32-bit arch). For the larger value, however, you will still get the string representation.
This code will return an array of converted integers:
["abc", "94761178","790"].map(Int.init) // returns [ nil, 94761178, 790 ]
OR
["abc", "94761178","790"].map { Int($0) ?? 0 } // returns [ 0, 94761178, 790 ]
Get the following isInteger() function from the below stackoverflow post posted by corsiKa:
Determine if a String is an Integer in Java
And I think this is what you want to do (where nameOfArray is the array you want to pass)
void convertStrArrayToIntArray( int[] integerArray ) {
for (int i = 0; i < nameOfArray.length(); i++) {
if (!isInteger(nameOfArray[i])) {
integerArray[i] = nameOfArray[i].toString();
}
}
}