I'm having a brain cramp this afternoon. This should be easy.
I did read the docs.
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html
It's easy to convert single instances of Float <> CGFloat but I'm looking for a fast method to cast a LARGE array > 500,000 elements of [Float] to [CGFloat].
var sphereRadiusFloat:[Float] = [0.0,1.0,2.0]
var sphereRadiusCGFloat:[CGFloat] = []
sphereRadiusCGFloat = sphereRadiusFloat as CGFloat
The error is
CGFloat is not convertible to [CGFloat]
I also tried
sphereRadiusCGFloat = CGFloat(sphereRadiusFloat)
which gives error
Could not find an overload operator for 'init' that accepts supplied
arguments.
You can use map to do it as follow:
sphereRadiusCGFloat = sphereRadiusFloat.map{CGFloat($0)}
Related
I'm using Xcode 7.3.1 and Swift, and i'm trying to set a random number between 1 and 50 like that: variableName = random()%50
Then i have to move an ImageView in the Y axe of that random value:
imageviewName.center.y = imageviewName.center.y - variableName
But it gives me the following error: "cannot convert value of type 'int' to expected argument type 'CGFloat'.
So I declared the variable like that:
var RandomSquirrel2 = CGFloat() but it still doesn't wok.
How can I generate a random number in Swift?
You need to covert the Int to CGFloat
imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)
You need to cast variableName to CGFloat. because random() returns an Int and not A CGFloat.
imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)
I have an array with Int values. In this array I need to get the highest value. Until here I have no problem. But now I need to convert this value to a CGFloat.
let ordersPerHour = [hour0All, hour1All, hour2All, hour3All, hour4All, hour5All, hour6All, hour7All, hour8All, hour9All, hour10All, hour11All, hour12All, hour13All, hour14All, hour15All, hour16All, hour17All, hour18All, hour19All, hour20All, hour21All, hour22All, hour23All]
let maxOrdersPerHourVal = ordersPerHour.sort().suffix(1)
How can I convert ArraySlice to CGFloat? All I have tried failed :-(
let maxOrdersPerHourVal = ordersPerHour.sort.last!
or
let maxOrdersPerHourVal = ordersPerHour.max()
will get the max value in an array.
Then you can cast as normal var floatVal = CGFloat(maxOrdersPerHourVal) if you need to cast the value.
Don't use sort here. Just use max() (or maxElement() in older versions of Swift). That will return an Int rather than a slice.
I have converted a String to an Int by by using toInt(). I then tried multiplying it by 0.01, but I get an error that says Could not find an overload for '*' that accepts the supplied argument. Here is my code:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = str * 0.01
From reading other posts it seems that the answer has to do with the type. For example if the type is set as an Integer then it gets a similar error. I have tried changing the type to an Int, but that doesn't seem to solve the problem.
I have also tried setting the type for 'str' and 'pennyCount' as Floats and Doubles and all combinations of Floats, Doubles, and Ints. My guess is the the problem has to do with toInt() function's conversion of a String to an Integer.
Could someone help clarify what the issue may be?
Swift seems to be fairly picky about implied type casting, so in your example you're multiplying str (an Integer) by 0.01 (a Double) so to resolve the error, you'll need to cast it like this:
var str: Int = 0
var pennyCount = 0.00
str = pennyTextField.text.toInt()!
pennyCount = Double(str) * 0.01
I want to get a value of Int32 through an Int32 Pointer.
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
It is like every UnsafePointer<>. Example: NSErrorPointer which is an AutoreleasingUnsafePointer<NSError?> you can get the value with the memory attribute.
Use the attribute memory
var errPtr: UnsafePointer<NSError> = ...
var err: NSError = errPtr.memory // not optional
Solution to your example is very easy then:
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
y.memory // in the playground it shows 32 :-D
There is no dereference operator in Swift, in C it was the aterisk *, but that is not possible in Swift.
The documentation is very helpful.
The type UnsafePointer<Memory> has a subscript operator. Provided that the pointer points to something, subscript 0 always exists, so this works in a playground and it has the advantage that the reference guide has the subscript documented but not the memory property.
var result:Int32 = 32
var y = withUnsafePointer(&result, {(point:UnsafePointer<Int32>) -> UnsafePointer<Int32> in
return point
})
y[0] // 32
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"