ios swift concatenating function results with another string - ios

For multiline button text I believe you add "\n" to the string. However I'm having trouble concatenating my function results and the newlinetext
setTitle:
HomeVC.getFriendCount("2",id:"friendid") + "\n newlinetext"
I need help getting my function results concatenated with "\n newlinetext"

You didn't specify an error, so I'm not sure, but I'm betting getFriendCount returns a number.
Try this:
let count = HomeVC.getFriendCount("2",id:"friendid")
let title = "\(count)\n newlinetext"

I've already encountered this. There must be some problem with (string + string) because it just ignores \n, though I never understood why this is. You can fix it by using join function:
let stringsToJoin = [getFriendCount("2",id:"friendid"), "newlinetext"]
let nString = join("\n", stringsToJoin)
Hope it helps!

You can use NSString's stringByAppendingString method
let aString = NSString(string: HomeVC.getFriendCount("2",id:"friendid"))
let concatenatedString = aString.stringByAppendingString("\n newlinetext")

If your method
HomeVC.getFriendCount("2",id:"friendid")
returns and optional string, then you need to unwrap it before concatenating.
Try
HomeVC.getFriendCount("2",id:"friendid")! + "\n newlinetext"

Related

SWIFT: Replace double backslash with single backslash in a string

I have a string that has the value of "\\u{abc}" and I want to change it to "\u{abc}"
My code is as it follows
str = "\\u{abc}"
let newstr = str.remove(at: str.startIndex)
print(newstr)
The output is: u{abc}
How can I remove just the first one ?
I also tried using replacing occurrences and dropfirst
Does anyone know how to fix this
Thanks for your time
i am editing the answer sorry i made huge mistake, here is the correction
var str = "\\u{abc}"
print(str.replacingOccurrences(of: "\\", with: #"\"#))
ouput : \u{abc}
Let's go
if you try to just
print("\u")
Xcode will warn you: Expected hexadecimal code in braces after unicode escape.
so, Xcode expecting some hexadecimal value, and this is where the conflict begins
your solution, specifically with \U is:
let newstr = "\\" + str.dropFirst()
Full is:
var str = "\\u{abc}"
let newstr = "\\" + str.dropFirst()
print(newstr)

Non-optional expression of type 'String' used in a check for optionals

I am getting this warning from Xcode Swift 5, here is my code I don't get what is wrong, I use this to remove any new line or tab at the end of my String (line)
My code:
let url: String = String(line.filter { !" \n\t\r".contains($0) })
UPDATE
I was doing it inside an if let and was using the type cast operator here is the solution and the rest of code and an example of the line value.
let line = " http://test.com/testing.php \n"
if let url: String = line.filter({!" \n\t\r".contains($0)}) as String?
{
//More action here
}
Thank you
to me this line looks good, but you may be missing the parentheses for the string filter method. Here's two ways I did it in playground. Let me know if this works for you, or how I can help further.
var line = "\t Hello, line removal \n \t Another new line \n"
let filteredClosure = line.filter { (char) -> Bool in
return !"\n\t\r".contains(char)
}
let filterShorthand = line.filter({!"\n\t\r".contains($0)})
With the line you provided, I would expect white-space to be removed too. If that's what you're looking for, add a space inside the filter string: " \n\t\r"

correct way to create a lowercase search string swift 3

I need string to use in the search function in my app. I don´t have much coding experience, but get by by googling a lot, tutorials, and some trial and error.
The below approach works, it creates just what I need, but I noticed it slows down compiling time substantially, so I assume that there is a better/smarter way to do this? I did not get much in a way of answers by googling on this one.
let searchText: String? = ("\(self.noseTextView?.text)"
+"\(self.palateTextField?.text)"+"\(self.finishTextField?.text)"
+"\(self.overallTextField?.text)"+"\(self.otherTextField?.text)"
+"\(self.glassTextField?.text)"+"\(bottleName2)"
+"\(self.distilleryTextField?.text)").lowercased()
Anyone that can teach me a better way to achieve the same result?
Edit:
One answer adapted to my code, (or my interpretation of it from Özgür Ersil, below), that works.
//creates lowercase String for labels to save compiling time
func getText(textLabel: UILabel)->String{
return textLabel.text!.lowercased()
}
//creates lowercase String for TextFields to save compiling time
func getTextTF(ui: UITextField)->String{
return ui.text!.lowercased()
}
//creates lowercase String for TextViewsto save compiling time
func getTextTV(ui: UITextView)->String{
return ui.text!.lowercased()
}
let searchText: String = self.getTextTV(ui: self.noseTextView) +
self.getTextTF(ui: self.palateTextField) + self.getTextTF(ui:
self.finishTextField) +
self.getTextTF(ui: self.overallTextField) + self.getTextTF(ui:
self.otherTextField) +
self.getTextTF(ui: self.glassTextField) + self.getTextTF(ui: self.bottleName) +
self.getTextTF(ui: self.distilleryTextField)
I use this function to append optional strings into a single String
func append(optionalStrings arrStrings : [String?],separator: String = " ") -> String {
return arrStrings.flatMap{$0}.joined(separator: separator)
}
This function takes an array of optional Strings as parameter
flatMap is a higher order function purpose of which here is to eliminate the nil value in arrayStrings(if exists) and provide us a array of non-Optional Strings which we can join with joined(separator: String) method.
You can use this as
let arrOptionalStrings = [noseTextView?.text,
palateTextField?.text,
finishTextField?.text,
overallTextField?.text,
otherTextField?.text,
glassTextField?.text,
bottleName2,
distilleryTextField?.text
]
let searchText: String? = append(optionalStrings: [str1,str2].map({ $0?.lowercased() }))

Can't replacing string with string

I have UITableViewCell with detailTextLabel which contains string that i want to replace with empty space(in other words to delete).It looks like this:
cell.detailTextLabel?.text = newsModel.pubDate
Now, the problem is that when i write cell.detailTextLabel?.text?.stringByReplacingOccurrencesOfString("+0000", withString: " ")
its not working and compiler says:
"Result of call
'stringByReplacingOccurrencesOfString(_:withString:options:range:)' is
unused"
Anyone can tell me the solution?
Thanks
The stringByReplacingOccurencesOfString:withString: method returns a string that is the result of replacing your search string with the replacement. The warning means that you are calling a method with a non-void return value that you aren't using.
From the documentation (italics added by me for emphasis)
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
You can use this:
cell.detailTextLabel?.text = newsModel.pubDate.stringByReplacingOccurrencesOfString("+0000", withString: " ")
The reason you get this warning is because the method doesn't modify the original string and returns a new string, which you don't use. If you were to use
cell.detailTextLabel?.text? = cell.detailTextLabel?.text?.stringByReplacingOccurrencesOfString("+0000", withString: " ")
You wouldn't get the warning because you are assigning the return value to the cell text and therefore "using" the result of the call.
The two methods are exactly the same, except one is shorter.

AS2 - How do you remove part of a string

I want a simple function that can remove part of a string, eg:
var foo="oranges";
trace(removeStrings(foo,'rang'));
I want the above output as 'oes'. Any help will be greatly appreciated.
Thanks in advance
A quick solution for removing substrings is to use split with the string that you want to remove as delimiter and then join the result:
function removeSubString(str, remove):String {
return str.split(remove).join("");
}
Another way to do this is
function removeStrings(originalString, pattern):String
{
return originalString.replace(pattern, "");
}
For more information about Strings in AS3 you can visit:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html
I should mention that the code above is not going to change your String, so if you need to use the property originalString with the new value you should use:
originalString = removeStrings(originalString, pattern);
The second thing that I should mention is that the replace method will replace the first appearance of the pattern, so if you need to replace every match of the pattern you should do something like
while(originalString.search(pattern) != -1)
{
originalString = removeStrings(originalString, pattern);
}
Hope this will help!
Ivan Marinov
I'm using by long time this snippet, which as the advantage to be available to all string objects on your movie:
String.prototype.replace = function(pattern, replacement) {
return this.split(pattern).join(replacement);
}
can be used in this way:
var str = "hello world";
var newstr = str.replace("world", "abc");
trace(newstr);
as you can see the string class have been extended with the replace method.

Resources