How to convert Int32 to String in Swift 4? - swift

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)

Related

How to retrieve an int-type data from firebase to xcode? (Error: Cannot convert value of type 'String' to expected argument type 'Int')

I was trying to fetch data from firebase to my xcode project. The only fields I have are 'userName', 'age', and 'number'. I was trying to append the values into arrays userNames, ages, and numbers. However, I get the error Error: Cannot convert value of type 'String' to expected argument type 'Int in the appending age and number lines. They both have been entered as Int types in the database.
I thought about converting the values of the database into Int types since I think Xcode is taking them as String types? I tried, but I think my code itself was wrong so I couldn't solve it. I would appreciate the help!
func fetchData () {
let database = Firestore.firestore()
database.collection("users").addSnapshotListener {(snap, Error) in
if Error != nil {
print("Error")
return
}
for i in snap!.documentChanges {
let documentID = i.document.documentID
let userName = i.document.get("userName")
let age = i.document.get("age")
let number = i.document.get("number")
DispatchQueue.main.async {
self.userNames.append("\(userName)")
self.ages.append("\(Int(age))") // error line
self.numbers.append("Int\(number)") // error line
}
}
}
}
You can try to coerce the data into the types you want by using as?. (get returns Any? by default)
let userName = i.document.get("userName") as? String
let age = i.document.get("age") as? Int
let number = i.document.get("number") as? Int
Keep in mind that you'll end up with Optional values, so you'll need to have a fallback in case you don't get the type you expect.
If you wanted to provide defaults, you could do:
let userName = i.document.get("userName") as? String ?? ""
let age = i.document.get("age") as? Int ?? 0
let number = i.document.get("number") as? Int ?? 0
Then, later:
self.userNames.append(userName)
self.ages.append(age)
Note that your compilation errors were happening because you were trying to store String values ("") in an [Int]
In general, rather than storing all of these in separate arrays, you may want to look into making a struct to represent your data and storing a single array with that type. See this answer for an example: https://stackoverflow.com/a/67712824/560942
And, the Firestore documentation on custom objects: https://firebase.google.com/docs/firestore/manage-data/add-data#custom_objects

Swift Convert Optional String to Int or Int32 (Unwrapping optionals question)

I am trying to read a string and convert it to an int. I have a solution but it seems way too complicated. I guess I am still trying to wrap my head around unwrapping.
I have posted code below along with the compiler errors that I get with each solution.
In this example I try to read a string from UserDefaults and convert to an integer value.
static func GetSelectedSessionNum() -> Int32 {
var sessionNum : Int32 = 0
let defaults = UserDefaults.standard
let optionalString: String? = defaults.string(forKey: "selectedSessionNum")
// this works but it's too complicated
if let string = optionalString, let myInt = Int32(string) {
return myInt
}
return 0
// Error : optional String? must be unwrapped to a value of type 'String'
let t : String = defaults.string(forKey: "selectedSessionNum")
if let s : String = defaults.string(forKey: "selectedSessionNum") {
// error - Int32? must be unwrapped to a value of Int32
return Int32(s)
}
return 0
}
You need to cast to non optional Int32 in order to match your return type.
You can use any optional binding approach, or change your return type to Int32?
If you want an uncomplicated solution save selectedSessionNum as Int
static func getSelectedSessionNum() -> Int32 {
return Int32(UserDefaults.standard.integer(forKey: "selectedSessionNum"))
}
otherwise double optional binding
if let string = UserDefaults.standard.string(forKey: "selectedSessionNum"), let myInt = Int32(string) {
return myInt
}
or the nil coalescing operator
if let string = UserDefaults.standard.string(forKey: "selectedSessionNum") {
return Int32(string) ?? 0
}
is the proper way
If you want to avoid optional bindings, you can use flatMap, when called on Optional's it allows you to convert one optional to another:
return UserDefaults.standard.string(forKey: "selectedSessionNum").flatMap(Int32.init) ?? 0
You'd also need the ?? (nil coalescing operator) to cover the scenarios where either the initializer fails, or the value is not present in user defaults.

How to convert string to UInt32?

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

Swift3: Proper way to convert string to null-terminated C-string

I am interfacing with libxml2 in swift, and the C APIs binding (still) produce UnsafePointer<Int8>! for c-strings. Whereas Swift APIs normally result in UnsafePointer<UInt8>!.
So my question is - am I doing the string to null-terminated C-string in a proper way?
let cfilePath = unsafeBitCast(myStringString.nulTerminatedUTF8.withUnsafeBufferPointer { $0.baseAddress }, to: UnsafePointer<Int8>.self)
Should I instead prefer using some other method instead of just bypassing Swift type checking with interpreting UInt8 bytes as Int8 bytes?
I'm not sure this solves your problem exactly but for a project where I am sending strings over bluetooth this did the trick:
extension String {
var nullTerminated: Data? {
if var data = self.data(using: String.Encoding.utf8) {
data.append(0)
return data
}
return nil
}
}
Use like this
let data = "asfasf".nullTerminated
I can't find the function the other answers are referencing: nulTerminatedUTF8. Maybe it already does this.
don't use unsafeBitCast for that!!
let cstr = "alpha".nulTerminatedUTF8
let int8arr = cstr.map{ Int8(bitPattern: $0) }
let uint8arr = Array(cstr)
print(int8arr.dynamicType, uint8arr.dynamicType)
// Array<Int8> Array<UInt8>
update
let uint8: UInt8 = 200
let int8 = Int8(bitPattern: uint8)
print(uint8, int8)
// 200 -56

Why is my variable returning a nil after being converted to an int?

I'm taking data from an api and storing it in a string variable. When I print the variable it returns what I'm looking for but when I try to convert it to an int using the .toInt method it returns a nil?
func getWeather() {
let url = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
var urlContentArray = urlContent.componentsSeparatedByString("temperature value=\"")
var temperatureString = (urlContentArray[1].substringWithRange(NSRange(location: 0, length:6))) as String
println(temperatureString) // returns 272.32
var final = temperatureString.toInt()
println(final) //returns nil
println(temperatureString.toInt())
self.temperature.text = "\(temperatureString)"
}
}
task.resume()
}
Even simpler, though slightly a trick, you can use integerValue:
temperatureString.integerValue
Unlike toInt, integerValue will stop converting when it finds a non-digit (it also throws away leading spaces.
If temperatureString is a String (rather than an NSString), you'll need to push it over:
(temperatureString as NSString).integerValue
That's because 272.32 is not an integer.
You could convert it to a Float.
272.32 isn't an Integer. If your temperature string is an NSString, you can do this to convert it:
Int("272.32".floatValue)