How to decleare char *const argv[] in swift [duplicate] - swift

This question already has answers here:
How to pass an array of Swift strings to a C function taking a char ** parameter
(2 answers)
Closed 7 years ago.
I am trying to make a c style array of chars pointer like this:
*const argv[]
I figured out i have to use UnsafePointer<UnsafeMutablePointer<Int8>>
but i don't know how to initialize it.
How can i map this normal Array to UnsafePointer<UnsafeMutablePointer<Int8>> :
let argv = ["/usr/bin/printf", "BBB"]
Thank you

The easy way is to let Cocoa form the C strings for you:
let args = ["/usr/bin/printf","BBB"]
var cs = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(2)
for (ix,s) in args.enumerate() {
cs[ix] = UnsafeMutablePointer<Int8>((s as NSString).UTF8String)
}
var cs2 : UnsafePointer<UnsafeMutablePointer<Int8>> = UnsafePointer(cs)
Beware; cs does not contain copies. Its pointers are pointing right into the strings in args.

Related

How can I read system input in Swift easily

I'm beginner in Swift and am having a hard time dealing with Swift String.
It has many differences from other languages I think.
So, can somebody tell me why is this statement incorrect?
I want to read a Line and insert each one Integer to variable n, l
in C, like this -> scanf("%d %d", &n, &l);
var n, l : Int?
var read : String = readLine()!
n = Int(read[read.startIndex])
l = read[read.index(read.startIndex, offsetBy : 2)]
The best way to handle input for a cli tool in Swift is probably by using the official ArgumentParser library.
But a super naive implementation would involve something like:
Read the input
Split it using spaces
Try to parse into Ints
The following example is of course not something that could be used for anything other than learning...:
print("Please input 2 numbers separated by space:")
let read = readLine()
if let inputs = read?.split(separator: " ") // Split using space
.map(String.init) // Convert substring to string
.compactMap(Int.init), // Try to convert to Ints (get rid of nils)
inputs.count > 1 { // Ensure that we got at least 2 elements
let (n, l) = (inputs[0], inputs[1])
print(n, l)
} else {
// Handle the case
}

Is it possible to write a macro that expands an expression N times? (Where N is a constant) [duplicate]

This question already has answers here:
Is there a way to count with macros?
(4 answers)
Counting length of repetition in macro
(3 answers)
Using a macro to initialize a big array of non-Copy elements
(3 answers)
Closed 6 years ago.
Say we need to declare a fixed size array with values, where the size of the array is defined by a constant that may change depending on compile time settings.
So for example:
let my_array = expand_into_array!(j, ARRAY_SIZE, -v0[j] * f);
Where ARRAY_SIZE is a constant, for example:
const ARRAY_SIZE: usize = 3;
Could expand into something like...
let my_array = [
{let j = 0; {-v0[j] * f}},
{let j = 1; {-v0[j] * f}},
{let j = 2; {-v0[j] * f}},
];
Since the expression is a fixed size array, it may be possible to use pattern matching, for a limited number of items ... up to 32 for example.
Is it possible to write a macro that expands an expression N times, based on a constant integer?
Details...
Looking into this, I wrote a macro which defines an array, then fills it in, eg:
const ARRAY_SIZE: usize = 3;
macro_rules! expand_into_array {
($index_var:ident, $const_size:expr, $body:expr) => {
{
let mut tmp: [_; $const_size] = [0.0; $const_size];
for $index_var in 0..$const_size {
tmp[$index_var] = $body;
}
// TODO, check $body _never_ breaks.
tmp
}
}
}
pub fn negated_array(v0: &[f64; ARRAY_SIZE]) -> [f64; ARRAY_SIZE] {
expand_into_array!(j, ARRAY_SIZE, {
-v0[j]
})
}
This works as expected, and besides the wrinkle (that the $body expression could include a break). this works without problems.
However initializing the array to 0.0 isn't getting optimized out (changing this value shows up as changes when run with: cargo rustc --release -- --emit asm
I'd rather not use unsafe { std::mem::uninitialized }.
Update, from asking another question, it seems macros can only match against literals, and not constants.
So this is simply not possible with macros in Rust.

Proper swift 2.2 syntax with for loop [duplicate]

This question already has an answer here:
Replace c style for-loop in Swift 2.2.1
(1 answer)
Closed 6 years ago.
I wrote the following code in swift(2.2):
for var i = 2; sqrt(Double(num)) >= Double(i); i += 1 {.....}
However, I keep getting a warning message which reads "c-style for statement is deprecated and will be removed in future version of swift".
So, what is the proper way of writing the same loop is "Swift style"? Casting the value of num as double gives me error with "Swift style". Any suggestions?
Thank you.
You can refactor your deprecated C-style for loop using the for-in construct
for i in 2...Int(sqrt(Double(num))) { }
However if you really want to go essential try defining this operator to find the square root of an int rounded down to the closest int.
prefix operator √ {}
prefix func √ (number: Int) -> Int {
return Int(sqrt(Double(number)))
}
Now you can write your for loop this way
for i in 2...(√num) { }
The For loop in Swift 2.2 is re-designed for use in iterating over a sequence, such as ranges of numbers, items in an array, or characters in a string. The condition in your For loop is not easily converted into sequence or range, so it would be best to re-write it as a While loop.

"&" in "swap(&someInt, &anotherInt)". What does it represent? What is its function? [duplicate]

This question already has answers here:
What does an ampersand (&) mean in the Swift language?
(5 answers)
Closed 7 years ago.
I'm new to Swift and I'm trying to learn the concept of 'inout' keyword. I saw this code in "the swift programming language 2.1". My question is, why is there a "&" in "swap(&someInt, &anotherInt)". What does it represent? What is its function?
func swapTwoInts(inout a: Int, inout _ b: Int){
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swap(&someInt, &anotherInt)
print("someInt is now \(someInt) and anotherInt is now \(anotherInt)")
Just like passing by reference in C++, the ampersands in the calling bit of the code just tell the compiler that you give permission to function swapTwoInts to change both someInt and anotherInt. If you had not put the ampersands there, the code would not compile.

In Objective C what does the "^{ ... }" mean? [duplicate]

This question already has answers here:
What does this caret ^ syntax, with void on either side mean? [duplicate]
(4 answers)
Closed 9 years ago.
I keep seeing lines of code with ^{ some code } in it... I thought that maybe it allowed to run a function inline similar to a lambda function. But I can not find any documentation on it. Could someone please enlighten me?
It is a block.
See the documentation.
Tis a block!
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
To steal Apple's example:
int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
printf("%d", myBlock(3));
// prints "21"
Yes, a block indeed...
Here is a tutorial for people who are beginners to blocks!
As Apple states in their documentation:
You use the ^ operator to declare a block variable and to indicate the
beginning of a block literal. The body of the block itself is
contained within {}, as shown in this example (as usual with C, ;
indicates the end of the statement):
int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};