swift calling item from an array with a string [duplicate] - arrays

How to concatenate string in Swift?
In Objective-C we do like
NSString *string = #"Swift";
NSString *resultStr = [string stringByAppendingString:#" is a new Programming Language"];
or
NSString *resultStr=[NSString stringWithFormat:#"%# is a new Programming Language",string];
But I want to do this in Swift-language.

You can concatenate strings a number of ways:
let a = "Hello"
let b = "World"
let first = a + ", " + b
let second = "\(a), \(b)"
You could also do:
var c = "Hello"
c += ", World"
I'm sure there are more ways too.
Bit of description
let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.
var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).
Note
In reality let and var are very different from NSString and NSMutableString but it helps the analogy.

You can add a string in these ways:
str += ""
str = str + ""
str = str + str2
str = "" + ""
str = "\(variable)"
str = str + "\(variable)"
I think I named them all.

var language = "Swift"
var resultStr = "\(language) is a new programming language"

This will work too:
var string = "swift"
var resultStr = string + " is a new Programming Language"

\ this is being used to append one string to another string.
var first = "Hi"
var combineStr = "\(first) Start develop app for swift"
You can try this also:- + keyword.
var first = "Hi"
var combineStr = "+(first) Start develop app for swift"
Try this code.

let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"

Very Simple:
let StringA = "Hello"
let StringB = "World"
let ResultString = "\(StringA)\(StringB)"
println("Concatenated result = \(ResultString)")

You can now use stringByAppendingString in Swift.
var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

Xcode didn't accept optional strings added with a normal string. I wrote this extensions to solve that problem:
extension String {
mutating func addString(str: String) {
self = self + str
}
}
Then you can call it like:
var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is
However you could now also do something like this:
var str1: String?
var str1 = "hi"
var str2 = " my name is"
str1! += str2

It is called as String Interpolation.
It is way of creating NEW string with CONSTANTS, VARIABLE, LITERALS and EXPRESSIONS.
for examples:
let price = 3
let staringValue = "The price of \(price) mangoes is equal to \(price*price) "
also
let string1 = "anil"
let string2 = "gupta"
let fullName = string1 + string2 // fullName is equal to "anilgupta"
or
let fullName = "\(string1)\(string2)" // fullName is equal to "anilgupta"
it also mean as concatenating string values.
Hope this helps you.

I just switched from Objective-C to Swift (4), and I find that I often use:
let allWords = String(format:"%# %# %#",message.body!, message.subject!, message.senderName!)

Swift 5
You can achieve it using appending API. This returns a new string made by appending a given string to the receiver.
API Details : here
Use:
var text = "Hello"
text = text.appending(" Namaste")
Result:
Hello
Hello Namaste

To print the combined string using
Println("\(string1)\(string2)")
or String3 stores the output of combination of 2 strings
let strin3 = "\(string1)\(string2)"

One can also use stringByAppendingFormat in Swift.
var finalString : NSString = NSString(string: "Hello")
finalString = finalString.stringByAppendingFormat("%#", " World")
print(finalString) //Output:- Hello World
finalString = finalString.stringByAppendingFormat("%#", " Of People")
print(finalString) //Output:- Hello World Of People

Concatenation refers to the combining of Strings in Swift. Strings may contain texts, integers, or even emojis! There are many ways to String Concatenation. Let me enumerate some:
Same String
Using +=
This is useful if we want to add to an already existing String. For this to work, our String should be mutable or can be modified, thus declaring it as a Variable. For instance:
var myClassmates = "John, Jane"
myClassmates += ", Mark" // add a new Classmate
// Result: "John, Jane, Mark"
Different Strings
If we want to combine different Strings together, for instance:
let oldClassmates = "John, Jane"
let newClassmate = "Mark"
We can use any of the following:
1) Using +
let myClassmates = oldClassmates + ", " + newClassmate
// Result: "John, Jane, Mark"
Notice that the each String may be a Variable or a Constant. Declare it as a Constant if you're only gonna change the value once.
2) String Interpolation
let myClassmates = "\(oldClassmates), \(newClassmate)"
// Result: "John, Jane, Mark"
3) Appending
let myClassmates = oldClassmates.appending(newClassmate)
// Result: "John, Jane, Mark"
Refer to Strings & Characters from the Swift Book for more.
Update: Tested on Swift 5.1

Swift 4.2
You can also use an extension:
extension Array where Element == String? {
func compactConcate(separator: String) -> String {
return self.compactMap {
if let unwrappedString = $0,
unwrappedString.isEmpty {
return nil
} else {
return $0
}
}
.joined(separator: separator)
}
}
Use:
label.text = [m.firstName, m.lastName].compactConcate(separator: " ")
Result:
"The Man"
"The"
"Man"

From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.” :
To combine (concatenate) two strings, the simplest approach is to use the + operator:
let s = "hello"
let s2 = " world"
let greeting = s + s2
This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation).
The + operator comes with a += assignment shortcut; naturally, the variable on the left side must have been declared with var:
var s = "hello"
let s2 = " world"
s += s2
As an alternative to +=, you can call the append(_:) instance method:
var s = "hello"
let s2 = " world"
s.append(s2)
Another way of concatenating strings is with the joined(separator:) method. You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:
let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)

Swift 5:
Array of strings into a Single string
let array = ["Ramana","Meharshi","Awareness","Oneness","Enlightnment","Nothing"]
let joined = array.joined(separator: ",")

Swift concatenate strings
Several words about performance
UI Testing Bundle on iPhone 7(real device), iOS 14, -Onone(debug, without optimizations)[About]
var result = ""
for i in 0...count {
<concat_operation>
}
Count = 5_000
//Append
result.append(String(i)) //0.007s 39.322kB
//Plus Equal
result += String(i) //0.006s 19.661kB
//Plus
result = result + String(i) //0.130s 36.045kB
//Interpolation
result = "\(result)\(i)" //0.164s 16.384kB
//NSString
result = NSString(format: "%#%i", result, i) //0.354s 108.142kB
//NSMutableString
result.append(String(i)) //0.008s 19.661kB
Disable next tests:
Plus up to 100_000 ~10s
interpolation up to 100_000 ~10s
NSString up to 10_000 -> memory issues
Count = 1_000_000
//Append
result.append(String(i)) //0.566s 5894.979kB
//Plus Equal
result += String(i) //0.570s 5894.979kB
//NSMutableString
result.append(String(i)) //0.751s 5891.694kB
*Note about Convert Int to String
Source code
import XCTest
class StringTests: XCTestCase {
let count = 1_000_000
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
override func setUp() {
measureOptions.iterationCount = 5
}
func testAppend() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result.append(String(i))
}
}
}
func testPlusEqual() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result += String(i)
}
}
}
func testPlus() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = result + String(i)
}
}
}
func testInterpolation() {
var result = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = "\(result)\(i)"
}
}
}
//Up to 10_000
func testNSString() {
var result: NSString = ""
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result = NSString(format: "%#%i", result, i)
}
}
}
func testNSMutableString() {
let result = NSMutableString()
measure(metrics: metrics, options: measureOptions) {
for i in 0...count {
result.append(String(i))
}
}
}
}

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"
DISCLAIMER: I wrote this extension

In Swift 5 apple has introduces Raw Strings using # symbols.
Example:
print(#"My name is "XXX" and I'm "28"."#)
let name = "XXX"
print(#"My name is \#(name)."#)
symbol # is necessary after \. A regular \(name) will be interpreted as characters in the string.

Related

Swift: Adding leading zeroes certain numbers of an array [duplicate]

I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code:
for myInt in 1 ... 3 {
print("\(myInt)")
}
Currently the result of it is:
1
2
3
But I want it to be:
01
02
03
Is there a clean way of doing this within the Swift standard libraries?
Assuming you want a field length of 2 with leading zeros you'd do this:
import Foundation
for myInt in 1 ... 3 {
print(String(format: "%02d", myInt))
}
output:
01
02
03
This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit.
The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this:
let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
output:
03:15:07
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
#1. Using String's init(format:_:) initializer
Foundation provides Swift String a init(format:_:) initializer. init(format:_:) has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String formatted from Int with at least two integer digits by using init(format:_:):
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
#2. Using String's init(format:arguments:) initializer
Foundation provides Swift String a init(format:arguments:) initializer. init(format:arguments:) has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String formatted from Int with at least two integer digits by using init(format:arguments:):
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
#3. Using NumberFormatter
Foundation provides NumberFormatter. Apple states about it:
Instances of NSNumberFormatter format the textual representation of cells that contain NSNumber objects and convert textual representations of numeric values into NSNumber objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter that returns String? from a Int with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
For left padding add a string extension like this:
Swift 5.0 +
extension String {
func padLeft(totalWidth: Int, with byString: String) -> String {
let toPad = totalWidth - self.count
if toPad < 1 {
return self
}
return "".padding(toLength: toPad, withPad: byString, startingAt: 0) + self
}
}
Using this method:
for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}
Swift 3.0+
Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation
extension String {
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.characters.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.characters.count)
return padding + self
}
}
Usage:
let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"
Swift 5
#imanuo answers is already great, but if you are working with an application full of number, you can consider an extension like this:
extension String {
init(withInt int: Int, leadingZeros: Int = 2) {
self.init(format: "%0\(leadingZeros)d", int)
}
func leadingZeros(_ zeros: Int) -> String {
if let int = Int(self) {
return String(withInt: int, leadingZeros: zeros)
}
print("Warning: \(self) is not an Int")
return ""
}
}
In this way you can call wherever:
String(withInt: 3)
// prints 03
String(withInt: 23, leadingZeros: 4)
// prints 0023
"42".leadingZeros(2)
// prints 42
"54".leadingZeros(3)
// prints 054
Using Swift 5’s fancy new extendible interpolation:
extension DefaultStringInterpolation {
mutating func appendInterpolation(pad value: Int, toWidth width: Int, using paddingCharacter: Character = "0") {
appendInterpolation(String(format: "%\(paddingCharacter)\(width)d", value))
}
}
let pieCount = 3
print("I ate \(pad: pieCount, toWidth: 3, using: "0") pies") // => `I ate 003 pies`
print("I ate \(pad: 1205, toWidth: 3, using: "0") pies") // => `I ate 1205 pies`
in Xcode 8.3.2, iOS 10.3
Thats is good to now
Sample1:
let dayMoveRaw = 5
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05
Sample2:
let dayMoveRaw = 55
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
The other answers are good if you are dealing only with numbers using the format string, but this is good when you may have strings that need to be padded (although admittedly a little diffent than the question asked, seems similar in spirit). Also, be careful if the string is longer than the pad.
let str = "a str"
let padAmount = max(10, str.count)
String(repeatElement("-", count: padAmount - str.count)) + str
Output "-----a str"
The below code generates a 3 digits string with 0 padding in front:
import Foundation
var randomInt = Int.random(in: 0..<1000)
var str = String(randomInt)
var paddingZero = String(repeating: "0", count: 3 - str.count)
print(str, str.count, paddingZero + str)
Output:
5 1 005
88 2 088
647 3 647
Swift 4* and above you can try this also:
func leftPadding(valueString: String, toLength: Int, withPad: String = " ") -> String {
guard toLength > valueString.count else { return valueString }
let padding = String(repeating: withPad, count: toLength - valueString.count)
return padding + valueString
}
call the function:
leftPadding(valueString: "12", toLength: 5, withPad: "0")
Output:
"00012"
Details
Xcode 9.0.1, swift 4.0
Solutions
Data
import Foundation
let array = [0,1,2,3,4,5,6,7,8]
Solution 1
extension Int {
func getString(prefix: Int) -> String {
return "\(prefix)\(self)"
}
func getString(prefix: String) -> String {
return "\(prefix)\(self)"
}
}
for item in array {
print(item.getString(prefix: 0))
}
for item in array {
print(item.getString(prefix: "0x"))
}
Solution 2
for item in array {
print(String(repeatElement("0", count: 2)) + "\(item)")
}
Solution 3
extension String {
func repeate(count: Int, string: String? = nil) -> String {
if count > 1 {
let repeatedString = string ?? self
return repeatedString + repeate(count: count-1, string: repeatedString)
}
return self
}
}
for item in array {
print("0".repeate(count: 3) + "\(item)")
}
Unlike the other answers that use a formatter, you can also just add an "0" text in front of each number inside of the loop, like this:
for myInt in 1...3 {
println("0" + "\(myInt)")
}
But formatter is often better when you have to add suppose a designated amount of 0s for each seperate number. If you only need to add one 0, though, then it's really just your pick.

Typescript: How remove last item from array

I have an array :
["one-", "two-", "three-", "testing-"]
After converted into string
"one-,two-,three-,testing-"
How to remove last charecter hypen(-) after testing and how should i get new array.
Accepted output
["one-", "two-", "three-", "testing"]
Please help me.
For an elegant solution use .slice(0, -1) for the string:
let newString = "one-,two-,three-,testing-".slice(0, -1); // "one-,two-,three-,testing"
To get the new array, simply use .split(','):
let newArray = newString.split(','); // ["one-", "two-", "three-", "testing"]
Do this:
var str = "one-,two-,three-,testing-";
str = str.substring(0, str.length - 1);
to take the last character off of your string. Then, to make it into a list:
var newList = str.split(“,”);
const array = ["one-", "two-", "three-", "testing-"];
let DataStr = array.toString();
let OutputStr = DataStr.replace("-", "");
var res = OutputStr.split(",");
console.log(res);
try this

Closest-match string-array sorting in Swift

Using Swift4, I would like to sort a string-array according to the closest match to a given searchTerm. Important is to me that if the searchTerm can be found as an exact-match, then the returnArray should show this searchTerm upfront !
Example: Given the Array = ["Hello world", "Hello Jamaica", "Hello", "Family", "Hel"]
And the searchTerm = "Hello", the algorithm should return:
["Hello", "Hello world", "Hello Jamaica", "Hel", "Family"].
Approach 1:
I tried to use FuzzyMatching - and it somehow worked (i.e. it did sort the inputArray according to a given searchTerm, however it did not put the exact-matches upfront ! i.e. With FuzzyMatching I achieved a good sorting according to substring-matches and syntactic sorting. But it did not bring me the exact-matches upfront in the returnArray).
Approach 2:
Then I tried my own algorithm - (see code below). But if there are several strings in the array that all start with my searchTerm (i.e. have searchTerm as a prefix), then somehow my algo does not a good job.
static func bestMatchFilterdStringArray(inputArray: [String], searchTerm: String) -> [String] {
let matchingTerms = inputArray
.filter { $0.range(of: searchTerm, options: .caseInsensitive) != nil }
.sorted { ($0.hasPrefix(searchTerm) ? 0 : 1) < ($1.hasPrefix(searchTerm) ? 0 : 1) }
return matchingTerms
}
How is a "Closest-match string-array sorting" done in Swift4? Especially bringing me exact-matches upfront in the returnArray? Any help appreciated!
You can use Levenshtein distance score to compare your search term with every string in the array, and the one with the highest score will be the first term in your result array etc. Your result will be an array of strings sorted in descending order of the score.
Following extension to string can be used to get Levenshtein distance score. In this algorithm, higher the value, better the equality.
extension String {
func levenshteinDistanceScore(to string: String, ignoreCase: Bool = true, trimWhiteSpacesAndNewLines: Bool = true) -> Double {
var firstString = self
var secondString = string
if ignoreCase {
firstString = firstString.lowercased()
secondString = secondString.lowercased()
}
if trimWhiteSpacesAndNewLines {
firstString = firstString.trimmingCharacters(in: .whitespacesAndNewlines)
secondString = secondString.trimmingCharacters(in: .whitespacesAndNewlines)
}
let empty = [Int](repeating:0, count: secondString.count)
var last = [Int](0...secondString.count)
for (i, tLett) in firstString.enumerated() {
var cur = [i + 1] + empty
for (j, sLett) in secondString.enumerated() {
cur[j + 1] = tLett == sLett ? last[j] : Swift.min(last[j], last[j + 1], cur[j])+1
}
last = cur
}
// maximum string length between the two
let lowestScore = max(firstString.count, secondString.count)
if let validDistance = last.last {
return 1 - (Double(validDistance) / Double(lowestScore))
}
return 0.0
}
}

How to split a String into an array? String.split(",") results in unexpected data type/struct [duplicate]

From the documentation, it's not clear. In Java you could use the split method like so:
"some string 123 ffd".split("123");
Use split()
let mut split = "some string 123 ffd".split("123");
This gives an iterator, which you can loop over, or collect() into a vector.
for s in split {
println!("{}", s)
}
let vec = split.collect::<Vec<&str>>();
// OR
let vec: Vec<&str> = split.collect();
There are three simple ways:
By separator:
s.split("separator") | s.split('/') | s.split(char::is_numeric)
By whitespace:
s.split_whitespace()
By newlines:
s.lines()
By regex: (using regex crate)
Regex::new(r"\s").unwrap().split("one two three")
The result of each kind is an iterator:
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());
There is a special method split for struct String:
fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>
Split by char:
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
Split by string:
let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
Split by closure:
let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);
split returns an Iterator, which you can convert into a Vec using collect: split_line.collect::<Vec<_>>(). Going through an iterator instead of returning a Vec directly has several advantages:
split is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next(). This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".
split makes no assumption on the way you want to store the result. You can use a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.
There's also split_whitespace()
fn main() {
let words: Vec<&str> = " foo bar\t\nbaz ".split_whitespace().collect();
println!("{:?}", words);
// ["foo", "bar", "baz"]
}
The OP's question was how to split with a multi-character string and here is a way to get the results of part1 and part2 as Strings instead in a vector.
Here splitted with the non-ASCII character string "☄☃🤔" in place of "123":
let s = "☄☃🤔"; // also works with non-ASCII characters
let mut part1 = "some string ☄☃🤔 ffd".to_string();
let _t;
let part2;
if let Some(idx) = part1.find(s) {
part2 = part1.split_off(idx + s.len());
_t = part1.split_off(idx);
}
else {
part2 = "".to_string();
}
gets: part1 = "some string "
         part2 = " ffd"
If "☄☃🤔" not is found part1 contains the untouched original String and part2 is empty.
Here is a nice example in Rosetta Code -
Split a character string based on change of character - of how you can turn a short solution using split_off:
fn main() {
let mut part1 = "gHHH5YY++///\\".to_string();
if let Some(mut last) = part1.chars().next() {
let mut pos = 0;
while let Some(c) = part1.chars().find(|&c| {if c != last {true} else {pos += c.len_utf8(); false}}) {
let part2 = part1.split_off(pos);
print!("{}, ", part1);
part1 = part2;
last = c;
pos = 0;
}
}
println!("{}", part1);
}
into that
Task
Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right).
If you are looking for the Python-flavoured split where you tuple-unpack the two ends of the split string, you can do
if let Some((a, b)) = line.split_once(' ') {
// ...
}

Swift: Detect when first letter(s) of a string isn't equal to particular character?

I have a simple string. I want to be able to detect when any word within that particular string does not have a # at the start of it and if so, execute some code. I have give it a go but my solution seems to be a little glitchy and not very reliable. Sometimes it executes the correct line and sometimes it doesn't. Is there a more efficient way to do this? Thank you guys.
extension Collection where Iterator.Element == String {
var initials: [String] {
return map{String($0.characters.prefix(1))}
}
}
let string: String = "Hello this is a #test"
let stringArray = string.components(separatedBy: " ")
print(stringArray.count)
let array = Array(stringArray)
let firstLetter = array.initials
for letter in firstLetter {
if letter != "#" {
print("tell user to add hashtag")
} else {
print("successful")
}
}
Here's a simpler approach using String's hasPrefix() method:
let string = "Hello this is a #test"
for word in string.components(separatedBy: " ") {
if !word.hasPrefix("#") {
print("tell user to add hashtag")
} else {
print("successful")
}
}

Resources