TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift isEmpty String (characters.count Is Zero)

Use the isEmpty method to test for zero-length strings. Test characters.count.
IsEmpty. A string can have many characters. But a valid string can also have zero characters. This is an empty string. With the isEmpty method we can test for empty strings.
First example. To create an empty string, we use the String() initializer. We can test for an empty string with isEmpty. The isEmpty property returns true or false.

Tip: To see if a string is not empty, we use the exclamation mark to negate the result of isEmpty in an if-statement.

Swift program that uses empty string, isEmpty var example = String() // The string is currently empty. if example.isEmpty { print("No characters in string") } // Now isEmpty will return false. example = "frog" if !example.isEmpty { print("Not empty now") } Output No characters in string Not empty now
Characters.count. With characters.count we get the count of characters in a string—its length. An empty string always has a length of 0.

So: We can use characters.count instead of the isEmpty property on strings to test for emptiness.

Swift program that uses characters.count, isEmpty // Test the characters count and isEmpty. print("::ON EMPTY STRING::") var example = String() print(example.characters.count) print(example.isEmpty) print("::ON 1-CHAR STRING::") example = "x" print(example.characters.count) print(example.isEmpty) Output ::ON EMPTY STRING:: 0 true ::ON 1-CHAR STRING:: 1 false
Optional. Instead of empty strings, we can use an Optional String. So if no result is found, we can return the nil value. We can use "if let" then to access the string safely.Optional
A summary. Methods can return a String, but a String cannot be nil—only an Optional string can be nil. So with empty strings (tested by isEmpty) we can signify "no result."
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf