I have a string that is actually a phone number. This string is stored as variable PhoneNumber in my database.
I want to convert this to a type phoneNumber() and then format it using the PhoneNumberKit and then put it back into a label as a string
How should i do this?
Convert the string to integer and then convert the string to phoneNumber struct present in phone number kit?
or is there anyway of simply passing the string itself to format function in phone Numberkit?
I have not written a full code yet. So this is what i have in my code:
func formatTOPhoneNumber(){
// userNumber is the string that is phone number
var userNumber = User.shared.phoneNumber
var num = (userNumber! as NSString).integerValue
}
The PhoneNumberKit library works with strings. Use the parse method to convert it into a PhoneNumber object. Then use the format function to convert it into a string:
var formattedString = ""
do {
let phoneNumberKit = PhoneNumberKit()
let phoneNumber = try phoneNumberKit.parse(userNumber)
formattedString = phoneNumberKit.format(phoneNumber, toType: .e164)
}
catch {
print("Generic parser error")
}
Try reading the documentation before asking a question, you might attract some downvotes when you haven't done any prior research.
Related
I have an input string "+20" and I am trying to pass that as query parameter in url.
So I am trying to encode the myInputString by doing
let s1 = myInputString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
But in the debugger, the string s1 still shows as '+20' instead of '%2B20'
Is there something I did wrong?
As already mentioned by matt + is a legal URL character. If you really need to encode it you would need to create your own custom urlQueryAllowed and subtract the plus sign from it:
extension CharacterSet {
static let allowedCharacters = urlQueryAllowed.subtracting(.init(charactersIn: "+"))
}
let myInputString = "+20"
let s1 = myInputString.addingPercentEncoding(withAllowedCharacters: .allowedCharacters) // "%2B20"
I got homework and I can't handle it. What I need?
I have a project that uses two languages (English, Spanish). The project has 2 Locolizable.strings files for two languages.
Example string:
"OrderDetails_IPText" = "IP: %#";
I understand %# is a string or some object, it does not matter. The problem is in people who help me with the translation of texts into different languages.
When they fill in the translation file, they see:
%#
They do not understand what I want to add there. This could be an email address or something else. People who translate the text gave me the task to implement a function that will take into account such nuances. They even offered some implementation, something like this:
func pffffff(format: something, ["key" : value] -> Id : value
Probably it should be an extension for String.
If you do not understand, thanks for watching this question. I did not understand anything.
We advised that you need to change this func:
func L (_ key: String, value: String = "") -> String
{
let str = NSLocalizedString(key, value: value, comment: "")
return str
}
You can create something like this.
extension String {
func yourFunction () {}
}
But I would recommend you not to use %# or any other character in localization string. You can always use replace string function with when the string contains any variable
For eg:
"We have sent an OTP at [VARIABLEA]"
Then while displaying just look for [VARIABLEA] and replace with actual value
I found a way out of this situation.
public extension String {
/* Creates the string representation of the poo with requested size.
- parameter format: string format with key
- returns: localizable string
*/
public init(format: String, keyArguments: [String: Any]) {
self = format
keyArguments.forEach {
self = self.replacingOccurrences(of: "{\($0.key)}", with: "\($0.value)", options: .caseInsensitive)
}
}
}
Was:
let asd = String(format: "Hi, %#! %d", "Arnold", 2)
Now:
let str = String(format: "Hi, {User_Name}! How are you, {user_name}?", keyArguments: ["user_name" : "Arnold", "number": 5.6])
I am having difficulty in converting an Int32 to String. I tried to following:
String(cartItem?.quantity)
"\(cartItem?.quantity)"
but no luck.
cart.quantity is of type Int32.
quantity is an attribute of cart in the CoreData model.
The question isn't clear but what I think this issue boils down to is that you can't init a string with an optional value.
So either do as #matt suggested and force unwrap the cartItem
String(cartItem!.quantity)
or supply a default value
String(cartItem?.quantity ?? 0)
Of course if you need to handle the fact that you might not have a cart then it is better to do it like
if let cart = cartItem {
let str = "\(cart.quantity)" //or String(cart.quantity)
//do stuff with str
} else {
//handle no cart state
}
you can by declare string and data
var arrayOf32Int: [UInt32] = [1,32,100,984,13,542]
let data = Data(bytes: arrayOf32Int, count: arrayOf32Int.count * MemoryLayout<UInt32>.stride)
let string = String(data: data, encoding: .utf32LittleEndian)!
print(string)
I am a beginner in swift and I am having a problem with convering string to UInt32.
let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue
if Generator == 1 {
NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String!
NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
Picture = ReadableJSON ["People"] [Person] ["E1"].string as String!
} else {
let RGen = arc4random_uniform ("\(Generator)") // here is the error
}
Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32.
The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.
arc4random_uniform(UInt32)
accept an UInt32 value but you are passing an String value to it
this converts your number to string
"\(Generator)"
the last line should be like this
let RGen = arc4random_uniform (UInt32(Generator))
and if you want to 'RGen' is an String you can do it this way
"\(RGen)"
String(RGen)
var RGen= 0
let RGen =int( arc4random_uniform ("\(Generator)") )
or
let RGen =( arc4random_uniform ("(Generator)") ).toInt
Look here
This formats my emoji perfectly:
lblEmoji!.text = String(format: "%C", 0xe04f)
However, as soon as I change the string to my son array it does not format correctly as an emoji
lblEmoji!.text = questionArray.objectAtIndex(currQuestionCount-1).valueForKey("quesimage") as? String;(format: "%C", 0xe04f)
Where is it I am going wrong?
String;(format: "%C", 0xe04f) is wrong. I don't even know what you're trying to do here.
If the objects in questionArray have a String variable quesimage (which is your emoji value), why not just take that directly without initializing a new String?
if let str = questionArray.objectAtIndex(currQuestionCount-1).valueForKey("quesimage") as? String {
lblEmoji!.text = str
}
or if you need to use a format string:
lblEmoji!.text = String(format: "%C", str)
If quesimage is a regular String representation of a UTF8 string, use a format string like so:
let utf8str = "0xe04f" // your value coming from quesimage
let emojiStr = String(format: "%C", arguments: [utf8str])
print(emojiStr) // ⑰
lblEmoji!.text = emojiStr