how to create a CStirng from ConstUnsafePointer in Swift - ios

i know CString can init with UnsafePointer ,but how to create it with ConstUnsafePointer
the error of the code: ConstUnsafePointer is not convertible to UnsafePointer
var result:ConstUnsafePointer = sqlite3_column_text(stmt, num)
let cstr:CString = CString(result)
or how to convert it to UnsafePointer

You just need to go through UnsafePointer:
var result: ConstUnsafePointer<UInt8> = sqlite3_column_text(stmt, num)
let cstr: CString = CString(UnsafePointer<UInt8>(result))

Please replace LENGTH with your variable.
var result: ConstUnsafePointer = sqlite3_column_text(stmt, num)
var resultToString: NSString = NSString(bytes: result, length: LENGTH, encoding: NSUTF8StringEncoding)
var cstring: CString = resultToString.UTF8String

Related

How can I change a UILabel into a number programmatically? [duplicate]

I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
Converting Int to String:
let x : Int = 42
var myString = String(x)
And the other way around - converting String to Int:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Here are 4 methods:
var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description
I can imagine that some people will have an issue with ss. But if you were looking to build a string containing other content then why not.
In Swift 3.0:
var value: Int = 10
var string = String(describing: value)
Swift 4:
let x:Int = 45
let str:String = String(describing: x)
Developer.Apple.com > String > init(describing:)
The String(describing:) initializer is the preferred way to convert an instance of any type to a string.
Custom String Convertible
Just for completeness, you can also use:
let x = 10.description
or any other value that supports a description.
Swift 4:
Trying to show the value in label without Optional() word.
here x is a Int value using.
let str:String = String(x ?? 0)
To save yourself time and hassle in the future you can make an Int extension. Typically I create a shared code file where I put extensions, enums, and other fun stuff. Here is what the extension code looks like:
extension Int
{
func toString() -> String
{
var myString = String(self)
return myString
}
}
Then later when you want to convert an int to a string you can just do something like:
var myNumber = 0
var myNumberAsString = myNumber.toString()
in swift 3.0 this is how we can convert Int to String and String to Int
//convert Integer to String in Swift 3.0
let theIntegerValue :Int = 123 // this can be var also
let theStringValue :String = String(theIntegerValue)
//convert String to Integere in Swift 3.0
let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
for whatever reason the accepted answer did not work for me. I went with this approach:
var myInt:Int = 10
var myString:String = toString(myInt)
Multiple ways to do this :
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
let intAsString = 45.description // "45"
let stringAsInt = Int("45") // 45
Swift 2:
var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)
Swift String performance
A little bit about performance
UI Testing Bundle on iPhone 7(real device) with iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
iam using this simple approach
String to Int:
var a = Int()
var string1 = String("1")
a = string1.toInt()
and from Int to String:
var a = Int()
a = 1
var string1 = String()
string1= "\(a)"
Convert Unicode Int to String
For those who want to convert an Int to a Unicode string, you can do the following:
let myInteger: Int = 97
// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
return ""
}
// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)
// results
print(myString) // a
Or alternatively:
let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
let myString = String(myUnicodeScalar)
}
I prefer using String Interpolation
let x = 45
let string = "\(x)"
Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions
let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
exampleLabel.text = String(yourInt)
To convert String into Int
var numberA = Int("10")
Print(numberA) // It will print 10
To covert Int into String
var numberA = 10
1st way)
print("numberA is \(numberA)") // It will print 10
2nd way)
var strSomeNumber = String(numberA)
or
var strSomeNumber = "\(numberA)"
let a =123456888
var str = String(a)
OR
var str = a as! String
In swift 3.0, you may change integer to string as given below
let a:String = String(stringInterpolationSegment: 15)
Another way is
let number: Int = 15
let _numberInStringFormate: String = String(number)
//or any integer number in place of 15
If you like swift extension, you can add following code
extension Int
{
var string:String {
get {
return String(self)
}
}
}
then, you can get string by the method you just added
var x = 1234
var s = x.string
let Str = "12"
let num: Int = 0
num = Int (str)

Swift3 convert string value to hexadecimal string

I am new to Swift and I want to convert a string into hexadecimal string. I have found a Objective-C function to a string into hexadecimal.
NSString * str = #"Say Hello to My Little Friend";
NSString * hexString = [NSString stringWithFormat:#"%#",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
for (NSString * toRemove in [NSArray arrayWithObjects:#"<", #">", #" ", nil])
hexString = [hexString stringByReplacingOccurrencesOfString:toRemove withString:#""];
NSLog(#"hexStr:%#", hexString);
Now I am unable to convert this function in Swift. Currently I am using Swift3.
Please someone can do this for me?
This produces the same output as the ObjC version
let str = "Say Hello to My Little Friend"
let data = Data(str.utf8)
let hexString = data.map{ String(format:"%02x", $0) }.joined()
Details
Xcode 11.2.1 (11B500), Swift 5.1
Solution
extension String {
func toHexEncodedString(uppercase: Bool = true, prefix: String = "", separator: String = "") -> String {
return unicodeScalars.map { prefix + .init($0.value, radix: 16, uppercase: uppercase) } .joined(separator: separator)
}
}
Usage
let str = "Hello, playground"
print(str.toHexEncodedString()) // 48656C6C6F2C20706C617967726F756E64
print(str.toHexEncodedString(uppercase: false, prefix: "0x", separator: " ")) // 0x48 0x65 0x6c 0x6c 0x6f 0x2c 0x20 0x70 0x6c 0x61 0x79 0x67 0x72 0x6f 0x75 0x6e 0x64
Convert your string to NSData like this.
let myString = "ABCDEF"
let data = myString.dataUsingEncoding(NSUTF8StringEncoding)
Then convert the NSData to hexadecimal string using following method -
func hexFromData(data:NSData) -> String {
let p = UnsafePointer<UInt8>(data.bytes)
let len = data.length
var str: String = String()
for i in 0...len-1 {
str += String(format: "%02.2X", p[i])
}
return str
}
Hope this helped.
Please try this,
let string = "Say Hello to My Little Friend"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
print(data)
and its output is:
Optional(<53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>)
Swift 3
let string = "Hello World!"
let data = string.data(using: String.Encoding.utf8)
let hexString = data?.hex
extension Data {
var hex: String {
var string = ""
#if swift(>=3.1)
enumerateBytes { pointer, index, _ in
for i in index..<pointer.count {
string += String(format: "%02x", pointer[i])
}
}
#else
enumerateBytes { pointer, count, _ in
for i in 0..<count {
string += String(format: "%02x", pointer[i])
}
}
#endif
return string
}
}

convert byte array to UIImage in Swift

I want to convert byte array to UIImage in my project.
For that I found something here.
After that I tried to convert that code in swift but failed.
Here is my swift version of the code.
func convierteImagen(cadenaImagen: NSMutableString) -> UIImage {
var strings: [AnyObject] = cadenaImagen.componentsSeparatedByString(",")
let c: UInt = UInt(strings.count)
var bytes = [UInt8]()
for (var i = 0; i < Int(c); i += 1) {
let str: String = strings[i] as! String
let byte: Int = Int(str)!
bytes.append(UInt8(byte))
// bytes[i] = UInt8(byte)
}
let datos: NSData = NSData(bytes: bytes as [UInt8], length: Int(c))
let image: UIImage = UIImage(data: datos)!
return image
}
but I'm getting error:
EXC_BAD_INSTRUCTION
which is displayed in screenshot as follow.
Please help to solve this problem.
If you are using the example data that you quoted, those values are NOT UInts - they are signed Ints. Passing a negative number into UInt8() does indeed seem to cause a runtime crash - I would have thought it should return an optional. The answer is to use the initialiser using the bitPattern: signature, as shown in the Playground example below:
let o = Int8("-127")
print(o.dynamicType) // Optional(<Int8>)
// It's optional, so we need to unwrap it...
if let x = o {
print(x) // -127, as expected
//let b = UInt8(x) // Run time crash
let b = UInt8(bitPattern: x) // 129, as it should be
}
Therefore your function should be
func convierteImagen(cadenaImagen: String) -> UIImage? {
var strings = cadenaImagen.componentsSeparatedByString(",")
var bytes = [UInt8]()
for i in 0..< strings.count {
if let signedByte = Int8(strings[i]) {
bytes.append(UInt8(bitPattern: signedByte))
} else {
// Do something with this error condition
}
}
let datos: NSData = NSData(bytes: bytes, length: bytes.count)
return UIImage(data: datos) // Note it's optional. Don't force unwrap!!!
}

String to NSNumber in Swift

I found a method to convert String to NSNumber, but the code is in Objective-C. I have tried converting it to Swift but it is not working.
The code I am using:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:#"42222222222"];
and in Swift I am using it in this way:
var i = NSNumberFormatter.numberFromString("42")
But this code is not working. What am I doing wrong?
Swift 3.0
NSNumber(integer:myInteger) has changed to NSNumber(value:myInteger)
let someString = "42222222222"
if let myInteger = Int(someString) {
let myNumber = NSNumber(value:myInteger)
}
Swift 2.0
Use the Int() initialiser like this.
let someString = "42222222222"
if let myInteger = Int(someString) {
let myNumber = NSNumber(integer:myInteger)
print(myNumber)
} else {
print("'\(someString)' did not convert to an Int")
}
This can be done in one line if you already know the string will convert perfectly or you just don't care.
let myNumber = Int("42222222222")!
Swift 1.0
Use the toInt() method.
let someString = "42222222222"
if let myInteger = someString.toInt() {
let myNumber = NSNumber(integer:myInteger)
println(myNumber)
} else {
println("'\(someString)' did not convert to an Int")
}
Or do it just in one line:
NSNumberFormatter().numberFromString("55")!.decimalValue
In latest Swift:
let number = NumberFormatter().number(from: "1234")
Swift 2
Try this:
var num = NSNumber(int: Int32("22")!)
Swift 3.x
NSNumber(value: Int32("22")!)
You can use the following code if you must use NSNumberFormatter.
It's simpler to use Wezly's method.
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle;
if let number = formatter.numberFromString("42") {
println(number)
}
I do use extension in swift 3/4 and it's cool.
extension String {
var numberValue: NSNumber? {
if let value = Int(self) {
return NSNumber(value: value)
}
return nil
}
}
and then just use following code:
stringVariable.numberValue
What is cool is that you don't need a chain of if statements to unwrap the optional values.
For instance,
if let _ = stringVariable, let intValue = Int(stringVariable!) {
doSomething(NSNumber.init(value: intValue))
}
can be replaced by:
doSomething(stringVariable?.numberValue)
Swift 5
let myInt = NumberFormatter().number(from: "42")
("23" as NSString).integerValue
("23.5" as NSString).doubleValue
and so on .
Try Once
let myString = "123"
let myInt = NSNumber(value: Int(myString) ?? 0)

Swift language: How to call SecRandomCopyBytes

From Objective-C, I could do this:
NSMutableData *data = [NSMutableData dataWithLength:length];
int result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes);
When attempting this in Swift, I have the following:
let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes)
but I get this compiler error:
'Void' is not identical to 'UInt8'
The data.mutableBytes parameter is rejected because the types do not match, but I can't figure out how to coerce the parameter (and I'm presuming it's somehow safe to do).
This appears to work:
let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes))
Swift 5
let count: Int = <byteCount>
var data = Data(count: count)
let result = data.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, count, $0.baseAddress!)
}
Swift 4:
var data = Data(count: <count>)
let result = data.withUnsafeMutableBytes { mutableBytes in
SecRandomCopyBytes(kSecRandomDefault, data.count, mutableBytes)
}
Swift 4 version:
let count = 16
var data = Data(count: count)
_ = data.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, count, $0)
}

Resources