Writing in UnsafeMutablePointer in Swift 3 - ios

The code below was working in previous versions of Swift, now compiler rejects it.
I need this function to interop with Swift from ObjectiveC.
#objc public static func myFunc(jdUT: Double, _ lon: Double, _ lat: Double,
_ dayLen: Double, _ SbhDeg: Double, _ MgrbDeg: Double,
omsk: UnsafeMutablePointer<Double>)
{
var z = somefuncion()
// this line gives this error : Cannot assign to property: 'omsk' is a 'let' constant
omsk.memory=z;
}

The error message is misleading. The memory property of
Unsafe(Mutable)Pointer has been renamed to pointee in Swift 3:
let z = someFunction()
omsk.pointee = z

#objc public static func myFunc(jdUT: Double, _ lon: Double, _ lat: Double,
_ dayLen: Double, _ SbhDeg: Double, _ MgrbDeg: Double,
inout omsk: UnsafeMutablePointer<Double>)
{
var z = somefuncion()
// this line gives this error : Cannot assign to property: 'omsk' is a 'let' constant
omsk.memory=z;
}
Adding inout before the omsk parameter should work.

Related

The function returns the result before processing the completionHandler of another function, how to fix it? [duplicate]

This question already has answers here:
Returning data from async call in Swift function
(13 answers)
Closed 1 year ago.
I ran into such a problem, and I can't figure out what are the ways to solve this problem.
First, let's say I have the following function
func summ(x: Int, y: Int, completionHandler: #escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
Next, in another function, we want to somehow process the result of the above function and return the processed value.
func summ(x: Int, y: Int, completionHandler: #escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
func getResult(x: Int, y: Int) -> (String) {
let resultString: String = ""
summ(x, y) { result in
resultString = "Result: \(String(result))"
}
return resultString
}
But when I call let resultString = getResult(x = 15, y = 10) I just get an empty string. When trying to find an error, I realized that in this method it creates let resultString: String = "" and then immediately returns this variable return resultString, and only After that completionHandler starts working
MARK - The solution below does not suit me, because the methods that I indicated above are just an example, in a real project, I need to return the correct value from the function in order to use it further.
let resultString: String = ""
func summ(x: Int, y: Int, completionHandler: #escaping (Int) -> ()) {
let result: Int = x + y
completionHandler(result)
}
func getResult(x: Int, y: Int) {
summ(x, y) { result in
resultString = "Result: \(String(result))"
self.resultString = resultString
}
}
So it is returning "" because the sum func takes time to complete. In the getResult func since the sum func takes time to finished u will always return "" in the getResult func. So instead the getResult should look something like this.
func getResult(x: Int, y: Int, completion: (String) -> Void) {
let resultString: String = ""
summ(x, y) { result in
resultString = "Result: \(String(result))"
completion(resultString)
}
}

Cannot assign value of type '(_) -> ()' to type '((String, String, String, Int) -> ())?'

I have a closure defined like this,
public var onLogCompletion:((_ printLog:String,_ fileName:String,_ functionName:String,_ lineNumber:Int) -> ())? = nil
Which is updated like this,
fileprivate func printerCompletion(printLog:String, fileName:String, functionName: String, lineNumber:Int) -> Void {
if onLogCompletion != nil {
onLogCompletion!(printLog, getFileName(name: fileName), functionName, lineNumber)
}
}
And using it like this,
Printer.log.onLogCompletion = { (log) in
//print(log)
//print(log.0)
}
Error:
Cannot assign value of type '(_) -> ()' to type '((String, String, String, Int) -> ())?'
But this is giving me above error and not sure what to do?
The same is working fine with Swift 3.x.
The reason its not working in Swift 4 is because of Distinguish between single-tuple and multiple-argument function types(SE-0110).
If you still want to work in a way you are doing in Swift 3 than you need to set the function type's argument list to enclosed with Double parentheses like this.
public var onLogCompletion:(((String,String,String,Int)) -> ())? = nil
Now you all set to go
Printer.log.onLogCompletion = { (log) in
//print(log)
//print(log.0)
}

Mutating self (struct/enum) inside escaping closure in Swift 3.0

In swift 2.2, We could mutate a struct or enum within a closure, when it was inside a mutating function. But in swift 3.0 its no longer possible. I get the following error
closure cannot implicitly captured a mutating self parameter
Here is a code snippet,
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
test { (a) -> Void in
// Get the Error in the below line.
self.x = Double(a)
}
}
mutating func test(myClosure: #escaping (_ a: Double) -> Void) {
myClosure(3)
}
}
I get that value types are not supposed to be mutable. I have cases, where I do have to modify one variable in the struct within one of the functions, when I receive the API response. (In the completion closure)
Is what I was doing in swift 2.2, impossible or is there way to accomplish this?
The problem is that #escaping closures can be stored for later execution:
Escaping Closures
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. ...
One way that a closure can escape is by being stored in a variable that is defined outside the function....
Since the closure can be stored and live outside the scope of the function, the struct/enum inside the closure (self) will be copied (it is a value) as a parameter of the closure. And, if it was allowed to mutate, the closure could have an old copy of it, causing unwanted results.
So, in answer to your question, you cannot; unless you are able to remove "#escaping" (not your case because it's a 3rd party API)
Yeah, you can do something like this.
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
test { (a) -> Void in
self.x = Double(a)
}
}
mutating func test(myClosure: (_ a: Double) -> Void) {
myClosure(3)
}
}
Struct is value type. So when use as Model or ModelView, you can make up a closure with new Value to VC.
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
test { [x, y](a) -> Point in
// Get the Error in the below line.
return Point(x: Double(a), y: y)
}
}
mutating func test(myClosure: #escaping (_ a: Double) -> Point) {
self = myClosure(3)
}
}

Cannot invoke 'implode' with an argument list of type '(String)'

I have to port an older Swift 1.2 project to Swift 2.1 and the project uses ExSwift extensively. unfortunately ExSwift hasn't been updated for Swift 2.1 (is it abandoned? Last update was six months ago).
I'm getting the above error with this piece of code:
public func * (array: [String], separator: String) -> String {
return array.implode(separator)!
}
How can I fix it since array has no implodeWithSeparator method?
This functionality is provided by the
extension SequenceType where Generator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
#warn_unused_result
public func joinWithSeparator(separator: String) -> String
}
method:
public func * (array: [String], separator: String) -> String {
return array.joinWithSeparator(separator)
}
let x = ["a", "b", "c"] * ","
print(x) // a,b,c

Swift number generics?

I have this function that is going to calculate the hypotenuse from 2 numbers
func hypotenusa<T>(nr1: T, nr2: T) -> T {
return sqrt( pow(nr1, 2) + pow(nr2, 2) )
}
// v Simpler situation v
func addition<T>(nr1: T, nr2: T) -> T {
return nr1 + nr2
}
I want to use generics so I don't have to make 3 copies of this which uses Int, Float, Double separately
But this isn't working, I think generics is really difficult to work with, please help me :)
Swift generics aren't like C++ templates.
In C++, you can just try to use a parameterized type however you want, and it's not an error until the compiler tries to instantiate the template with some type that doesn't support what your template tries to do.
In Swift, the generic construct can only use a parameterized type in ways known to be valid when the generic construct is first parsed. You specify these "ways known to be valid" by constraining the parameterized type with protocols.
You cannot call sqrt or pow with generic-typed arguments, because those functions are not themselves generic. They have each two definitions:
func pow(_: Double, _: Double) -> Double
func pow(lhs: Float, rhs: Float) -> Float
func sqrt(x: Double) -> Double
func sqrt(x: Float) -> Float
You could write type-specific versions of hypotenusa:
func hypotenusa(a: Float, b: Float) -> Float
func hypotenusa(a: Double, b: Double) -> Double
func hypotenusa(a: CGFloat, b: CGFloat) -> CGFloat
I'm not sure why you'd create an Int version at all, since very few right triangles have integer hypotenuses.
Anyway, you don't need to define the Float and Double versions at all, because the standard library already provides a hypot function defined on Float and Double:
func hypot(_: Double, _: Double) -> Double
func hypot(lhs: Float, rhs: Float) -> Float
You could create another override for CGFloat:
func hypot(l: CGFloat, r: CGFloat) -> CGFloat {
return hypot(Double(l), Double(r))
}
As for your addition function, it has the same problem as your hypotenusa function: the + operator is not defined entirely generically. It has some generic definitions (unlike sqrt and pow), but those only cover the integer types (see IntegerArithmeticType). There's not generic definition of + that covers the floating-point types. Swift defines all of these versions of + with explicit types:
func +(lhs: Float, rhs: Float) -> Float
func +<T>(lhs: Int, rhs: UnsafePointer<T>) -> UnsafePointer<T>
func +<T>(lhs: UnsafePointer<T>, rhs: Int) -> UnsafePointer<T>
func +(lhs: Int, rhs: Int) -> Int
func +(lhs: UInt, rhs: UInt) -> UInt
func +(lhs: Int64, rhs: Int64) -> Int64
func +(lhs: UInt64, rhs: UInt64) -> UInt64
func +<T>(lhs: Int, rhs: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T>
func +<T>(lhs: UnsafeMutablePointer<T>, rhs: Int) -> UnsafeMutablePointer<T>
func +(lhs: Int32, rhs: Int32) -> Int32
func +(lhs: UInt32, rhs: UInt32) -> UInt32
func +(lhs: Int16, rhs: Int16) -> Int16
func +(lhs: UInt16, rhs: UInt16) -> UInt16
func +(lhs: Int8, rhs: Int8) -> Int8
func +(lhs: UInt8, rhs: UInt8) -> UInt8
func +(lhs: Double, rhs: Double) -> Double
func +(lhs: String, rhs: String) -> String
func +(lhs: Float80, rhs: Float80) -> Float80
With Swift 5, according to your needs, you can pick one of the following ways in order to solve your problem.
#1. Using FloatingPoint protocol as a parameter generic constraint
The Apple Developer Documentation for FloatingPoint shows the following hypotenuse function implementation as an example of FloatingPoint usage:
func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T {
return (a * a + b * b).squareRoot()
}
let (dx, dy) = (3.0, 4.0)
let result = hypotenuse(dx, dy)
print(result) // prints: 5.0
#2. Using AdditiveArithmetic protocol as a parameter generic constraint
AdditiveArithmetic has the following declaration:
A type with values that support addition and subtraction.
The Playground sample code below shows a possible usage of AdditiveArithmetic as a function parameter generic constraint:
func addition<T: AdditiveArithmetic>(a: T, b: T) -> T {
return a + b
}
let result = addition(a: 3, b: 4)
print(result) // prints: 7
#3. Using Numeric protocol as a parameter generic constraint
Numeric has the following declaration:
A type with values that support multiplication.
The Playground sample code below shows a possible usage of Numeric as a function parameter generic constraint:
func multiply<T: Numeric>(a: T, b: T, c: T) -> T {
return a * b * c
}
let result = multiply(a: 3, b: 4, c: 5)
print(result) // prints: 60
Note that Numeric protocol inherit from AdditiveArithmetic protocol.
The Apple Developer Documentation contains a dedicated page for all numeric protocols: Numeric Protocols.
I think this is what you need:
You need to explicitly create a new protocol and extend the types you want (Int, Float, Double) to conform to the protocol. Than in your generic declaration you do
func addition<T: protocolJustCreated>(nr1: T, nr2: T) -> T {}
Read the answer I linked for a more complete answer. No need to repeat here.
Sqrt() and pow() both specify their parameters as either double or float. In order to meet your goal of using this one function for Int, Float, and Double you will need to also make generics of sqrt() and pow() functions.

Resources