I want add the " " symbols to my text data. text data is getting from textview.
I want remove the " " symbols from optional text. optional text is getting from text filed, how to remove and how to add the "" symbols in swift.......
The problem is that the string you are trying to log is typed as an optional (String?) rather than just a String. You need to unwrap it before logging it.
You can either use if let:
if let string = maybeString {
print(string)
}
Or (and this is what I prefer), you can use the ?? operator to provide a placeholder value to print in the case of the string being nil:
print(string ?? "(nil)")
Related
I need to filter the array of the Dictionary based on the search string. In Dictionary, I have a key "name", I need to compare the entered string in textfield to the name key in Dictionary.
func textChanged(textField: UITextField) {
if textField.text == "" {
self.filteredArrayStoreList = self.arrayStoreList
} else {
self.filteredArrayStoreList.removeAll()
print("Text: \(textField.text ?? "")")
let filteredArray = self.arrayStoreList.filter { ($0.name?.contains((textField.text ?? "")))!}
self.filteredArrayStoreList = filteredArray
self.noLocationFoundView.isHidden = true //filteredArrayStoreList.count == 0
}
self.searchLocationTabelView.reloadData()
}
In Dictionary, the name key value is " Vimal's ".
But in textfield, I will get the text as " Vimal‘s ". How to search for the single quotes.
' (ascii-39) is the normal quote, and ‘ (ascii-8216) is called "smart" or "curly" quote. this quote is the appear on iOS device keyboard.User can on/off this feature from settings
Settings -> General -> Keyboard-> Smart punctuation
That is the reason for not matching these 2 strings.You can do 2 things to solve your problem. Because we don't know app user's device on/off that feature
simply you can enter dictionary names without special characters
you can find and replace that smart/curl quote with normal quote before check
this is the example
let name:String = "vimal‘s"
print(name.replacingOccurrences(of: "‘", with: "'"))
//result "vimal's"
I am new to iOS development, while I was going through string interpolation. I want to know the clarification between these print statement's output:
var value = "5"
print("Values is: \(value)")
print("Values is:", value)
print("Values is: " + value)
Output is : Values is: 5
Values is: 5
Values is: 5
Practically all three forms do the same thing.
The differences are
String interpolation syntax. You can put everything within the inner parentheses which responds to the CustomStringConvertible protocol.
Variadic parameter syntax. print is declared func print(_ items: Any...,. Any... means you can pass multiple items comma separated which are treated as array.
String concatenation syntax : The strings are concatenated with the + operator
If 5 was Int rather than String forms 1 and 2 are valid but not form 3
For such a question, we should take a look at print(_:separator:terminator:) parameters:
1) items: is a variadic parameter of type Any, which means that you can pass zero or more items to it. Example:
print() // passing nothing
print("Hello") // passing single item (String)
print(101, 40.45, false, ["Hi", "Greetings"]) // passing multiple items
2) separator: the string to print between each item (as mentioned in its documentation). Example:
print(101, 40.45, false, ["Hi", "Greetings"], separator: " <=> ")
// 101<=>40.45<=>false<=>["Hi", "Greetings"]
3) terminator: the string to print after all items have been printed (as mentioned in its documentation). Example:
print(101, 40.45, false, ["Hi", "Greetings"], terminator: " ==>")
// 101 40.45 false ["Hi", "Greetings"] ==>
Back to your cases:
First, keep in mind that for all of your three cases you are passing only items parameter; It is valid -for sure- because separator and terminator have default values as " " and \n.
Now, for the first and third print statements
print("Values is: \(value)")
print("Values is: " + value)
what happens is: actually you are dealing with Strings, it is not about the print itself. You can do interpolation in strings as well as using the + for concatenating strings without the print:
// interpolation:
let name = "Jack"
let greetingMessage = "Greetings, \(name)"
print(greetingMessage) // => Greetings, Jack
// concatenating:
let concatenated = "Greetings" + ", " + "Sara"
print(concatenated) // => "Greetings" + ", " + "Sara"
Which means that you are passing a single String item, regardless of doing interpolation or concatenation for it.
You could also check The + function implementation in Swift. Basically, it is an append!
The second print statement:
print("Values is:", value)
What happens here is: you are passing two items; According to the default value for separator, the output is:
Values is: 5
As:
Values is: 5
^ ^^
| ||__ item #2
item #1 |
|
default separator (" ")
In this print statement output is the same but there is different like in first statement use \(value) variable within the string data.
The second statement append data in your string value with keep one space
The third statement just concat two value (it does not keep space between two value), In this statement "+" sign used as operator overloading to concat two value
let value = "5"
print("Values is: \(value)") //use variable value within string
print("Values is:", value) //append value, with keep one space
print("Values is: " + value) //just concat two value
var value = "5"
print("Values is: (value)")
// Print the value as a part of the the string. If you use print("Values is:(value)"), it will print the output without space.
print("Values is:", value)
// you do not need to add a separate space to add the value to sting. It will automatically add the value to the string with a space.
print("Values is: " + value)
// It will show error if you use integer value "Binary operator '+' cannot be applied to operands of type 'String' and 'Int'"
otherwise it will work. And if you want to concatenate int with sting you need to do something like below:-
print("Values is: " + String(value))
// it is normal concatenate number with string
All the above will print the exact
I have created my own class in Swift as below.
class Product: NSObject {
var product_id:Int?
var product_number:String?
var product_price:Float?
var product_descrption:String?
}
Now i am setting value in each property like this
let p=Product()
p.product_id=1
p.product_price=220.22
p.productdescrption="Some description"
p.product_number="W2_23_233"
But when i get the value from price then for price i get value like "Optional 220.22" But i don't get appended word "Optional" in description".So to resolve this i added "!" for unwrapping the value of float but i did not have to do this for String please tell why this is happening?
If you are printing any of these values should say Optional(...). If you are assigning the values to a label, that will not include the Optional(...), The reason that it shows Optional(...) when you print the value using print(), is just to show you its an optional. For safety, instead of using the !, try using if lets.
An example with your code,
if let id = p.product_id {
print(id) //Does not contain Optional()
}
You can also combine them, to do them all at one time. (Only do this if you don't want to print unless all values are non-nil)
if let id = p.product_id,
let price = p.product_price,
let description = p.productdescrption,
let productNumber = p.product_number {
//Enter code here that does something with these values
}
Note, if you aren't on swift 3, I believe you only have to write let on the first condition.
If you print any optional variable without unwrapping no matter what type it is, Optional will be appended to the variable's value.
print(p.product_price) will print Optional(220.220001)
print(p.product_descrption) will print Optional("Some description")
To print only value you need to unwrap the optional variables.
print(p.product_price!) will print 220.22
print(p.product_descrption!) will print Some description
This forced unwrapping will only work if the optionals does not contain nil. Otherwise it will give you a runtime error.
So to check for nil you can use if let statement.
No matter what type of variable. If you assign a value to an optional variable, It always enclosed with Optional(...)
Optional without forced unwrapping:
print("product_price = \(p.product_price) \n product_descrption = \(p.product_descrption)")
Output:
product_price = Optional(220.22)
product_descrption = Optional(Some description)
Optional with forced unwrapping:
print("product_price = \(p.product_price!) \n product_descrption = \(p.product_descrption!)")
Output:
product_price = 220.22
product_descrption = Some description
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.
I am very confused with unwrap fundamentals of Swift 2.0. I have bellow code to display last name string value from dictionary to label.
let lastName:String? = self.userDict.objectForKey("last_name")
self.lblLastName.text = "Last Name: " + lastName!
but some times this code run before value assign in to self.userDict at that time above code get self.userDict.objectForKey("last_name") nil and throw an error.
For solution i modified my code like bellow and keep that value unwrap but compiler don't take it as valid
let lastName:String? = self.userDict.objectForKey("last_name")
self.lblLastName.text = "Last Name: " + lastName? //--ERROR: Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
Please suggest me valid way to fulfil the requirement.
You need to provide a way to handle cases when dictionary has no value for key "last_name" and returns nil. Easiest way is to use nil coalescing operator ??:
The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
You could do something like:
let lastName: String = self.userDict.objectForKey("last_name") ?? "N/A"
self.lblLastName.text = "Last Name: " + lastName
You could also use Optional Binding to check if the retrieved value from dictionary is nil or not. Then you can assign the string to your label (lblLastName) conditionally.
if let lastName = self.userDict.objectForKey("last_name") {
self.lblLastName.text = "Last Name: " + lastName
} else {
self.lblLastName.text = "Last Name: " + "some other hard coded string"
}