I’m just learning swift and can’t seem to figure out a problem.
I’ve tried changing the function text but nothing seems to be working
func multiply(_ a: Double, _ b: Double) -> Double {
a * b
}
solution.swift:2:7: warning: result of operator '*' is unused
a * b
~ ^ ~ solution.swift:3:1: error: missing return in a function expected to return 'Double' } ^
That code uses the new feature introduced in Swift 5.1 - implicit returns from single expression functions. (New features in Swift 5.1)
Make sure you are using Swift 5.1/Xcode 11. If you are not, you have to write return:
func multiply(_ a: Double, _ b: Double) -> Double {
return a * b
}
Related
So in the "Swift Tour" (https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html) is a part about closures.
The code in their example is the following:
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
But when tryin to run this, you get following error: " error: use of unresolved identifier 'numbers' "
So my questions are:
What are closures/ Could anyone explain the usage of these?
What is wrong with the example (it´s the official code example of the Swift documentation..)
The array numbers is declared on line 12 of the previous code block. Each code block shown in that chapter builds on the one before. You can download the code as a playground
The functioning code block would be:
var numbers = [20, 19, 7, 12]
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
Closures are described in more detail in their own chapter but in summary:
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
In the case of the map function, the code in the closure operates on each element of the array in turn. It accepts the array element as input and returns an element for the output array.
You can return 0 for odd numbers using the modulo function
let evens = numbers.map({ (number: Int) -> Int in
if number % 2 == 0 {
return number
} else {
return 0
}
})
This question already has answers here:
Could not find an overload for '^' that accepts the supplied arguments
(2 answers)
Closed 6 years ago.
I'm using IBM's online Swift sandbox and I'm trying to run this code but it's giving me an error:
The code:
var a: Double = 1.0
var b: Double = 2.0
var c: Double = 3.0
var x: Double = 0.0
func x_func(a_var: Double, b_var: Double, c_var: Double) -> Double {
x = (-b + (b^2 - 4*a*c)^(1/2))/(2*a)
return x
}
print(x_func(a_var: a, b_var: b, c_var: c))
print(a)
print(b)
print(c)
The error:
<unknown>:0: error: unable to execute command: Killed
<unknown>:0: error: compile command failed due to signal (use -v to see invocation)
Could someone help me figure out what's wrong? I'm brand new to Swift, so I don't see an error here.
Try using pow when you want to use exponents, the ^ doesn't work with Swift for that. With Swift ^ produces bitwise XOR - not exponent.
import Foundation
var a: Double = 1.0
var b: Double = 2.0
var c: Double = 3.0
var x: Double = 0.0
func x_func(a_var: Double, b_var: Double, c_var: Double) -> Double {
x = (-b + pow((pow(b, 2) - 4*a*c), 1/2))/2*a
return x
}
Make sure when using things like IBM Sandbox, or HackerRank or whatever to import Foundation framework! I know it's easy to forget and can cause a lot of headache if you do.
Also, unless you're doing extra computation in your x_func method that you're not showing, you're asking for parameters to be passed in that you don't even use. You can either get rid of the properties, or change the function to not take in any variables - it would probably be more efficient to get rid of the properties and change it to something like this:
import Foundation
func x_func(a: Double, b: Double, c: Double) -> Double {
x = (-b + pow((pow(b, 2) - 4*a*c), 1/2))/2*a
return x
}
Getting the following error:
Binary operator '==' cannot be applied to operands of type 'UInt16' and '() -> UInt16'
in this section of code:
let array: [UInt16] = [3,4, 7]
let x = NSNumber(value: 4)
let option = array.filter { (test) -> Bool in
return test == x.uint16Value // compiler complains here
}
print(option) // "[4]"
Normally this type of error means two values of separate class are being compared. Here the compiler thinks I'm comparing a uint16 value with a function that returns a uint16 value.
What I mean to do is call NSNumber's uint16 property getter.
// defined in NSNumber
open var uint16Value: UInt16 { get }
I'm told to instead make a function call by adding parenthesis (e.g .uint16Value()). But this leads to the follow up error:
Cannot call value of non-function type 'UInt16'
I have dropped this exact code into a playground and it runs fantastically.
Has anyone else run into this? Or seen this type of behavior? Have you beaten it?
Update:
When setting to a local variable, no difference is made. I have recently run the migration tool from Swift 2.2 or 2.3 up to swift 3 in Xcode 8.0. It doesn't seem like there is anything wrong with syntax or migration.
let y = x.uint16Value
return test == y // compiler complains here
Apparently Xcode doesn't let me modify the UI (iOS) from a background thread. I have to type:
let res = somethingReturningaString()
dispatch_async(dispatch_get_main_queue(), {
self.txtError.text = res!
})
My idea was: 'hey, let's simplify my life and define a custom operator, so I can type something like:'
prefix operator ~> {}
prefix func ~> (closure: ()-> ()) {
dispatch_async(dispatch_get_main_queue(), closure)
}
//usage example
~> {self.txtError.text = res!}
Apparently the operator of type '()' cannot be applied to '()->()'
Does anybody know how to declare this to get this working?
The swift compiler got a little confused there. You must not ever separate a unary operator from its operand, meaning there must not be a whitespace in between.
Consider the following example code
let k = 12
~> {
self.txtError.text = res!
}
Swift now expects ~> to be a binary operand because there is a whitespace.
binary operator '~>' cannot be applied to operands of type 'Int' and '() -> ()'
If you insert a ; after the first line:
let k = 12;
~> {
self.txtError.text = res!
}
You receive something a little bit more helpful:
Unary operator cannot be separated from its operand
Which simply means that there must in fact be no whitespace.
Fix
Remove the whitespace:
~>{ self.txtError.text = res! }
For example, I have the following code:
let numberOfBlocks = 3
let blockWidth = SKSpriteNode(imageNamed: "image.png").size.width
let padding = 20.0
let offsetX : Float = (self.frame.size.width - (blockWidth * numberOfBlocks + padding * (numberOfBlocks-1))) / 2
I got the error:
'Double' is not convertible to 'UInt8'
Is there a way to implicitly convert the data type (maybe only for primitive data type)?
Edit:
I know how to do the explicit conversion by using constructor of particular type as Iducool suggested. But it's not a big help to my question because we even don't know where to add the conversions. I simplified my expression in playground:
The problem is in "padding" variable, the error message is
'Double' is not convertible to 'UInt8'.
So I did the conversion:
Then the problem is in "blockWidth" variable now.
I added the conversion again:
And error message is:
Type 'UInt8' does not conform to protocol 'FloatLiteralCovertible'
The final working expression is:
Is it simple and swift? I don't think so.
There is no implicitly cast in Swift.
Easy way of conversion in swift is using constructor of particular type.
Like if you want to get Float from double then you can use Float(doubleValue) and Same way if you want to convert float to integer then you can use Int(floatValue).
In your case:
let intValue = UInt8(doubleValue)
Beware that you will lose any value after the decimal point. So, choose a better way. Above conversion is just to help you in understanding.
Note that Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.
Swift doesn't support implicitly cast anymore in Xcode6 GM. Following answer only apply to Xcode6 beta version.
I don't want to talk about implicitly cast is good or bad, but you can have it if you really want with __conversion()
e.g. If you need UInt8 and Int be able to convert from Double
extension Double {
func __conversion() -> UInt8 { return UInt8(self) }
func __conversion() -> Int { return Int(self) }
// add more if you need to
}
xcrun swift
Welcome to Swift! Type :help for assistance.
1> extension Double {
2. func __conversion() -> UInt8 { return UInt8(self) }
3. }
4> var d = 1.0
d: Double = 1
5> var u8 : UInt8 = d
u8: UInt8 = 1
6>
Note: I won't put this in my production code. I only want to point out it if possible but not recommending it.
using bridgeToObjectiveC() method you can call the methods provided in Objective - C to convert from one primitive data type to another for e.g.
variable_name.bridgeToObjectiveC().intValue
will convert that variable named variable_name to integer
Implicit conversion is possible but with literals only and some conversions are available from the box e.g. Int -> Double:
let a = 3 // Int
let b = 100.5 // Double
// Doesn't work with variables
let c = a * b // Error: Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
// But this works, because Int(3) literal converts to Double(3.0) implicitly
let d = 3 * b // 301.5
If you want to make backward conversion Double -> Int you should extend Int with ExpressibleByFloatLiteral:
extension Int: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
// Double(100.5) converts to Int(100)
let e = a * 100.5 // 300
Even more it's possible to implicitly convert to any type from literals, for instance String -> URLRequest:
extension URLRequest: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(url: URL(string: value)!)
}
}
let request: URLRequest = "https://www.google.com"