問題描述
如果這能說明問題,這里是原始的 Objective-C 代碼.
In case this illuminates the problem, here's the original Objective-C code.
int x = (arc4random()%(int)(self.gameView.bounds.size.width*5)) - (int)self.gameView.bounds.size.width*2;
int y = self.gameView.bounds.size.height;
drop.center = CGPointMake(x, -y);
我從這段代碼開始.第 2 行和第 3 行很好,為了清楚起見,我稍后再展示它們.
I started out with this code. Lines 2 and 3 are fine, I'm presenting them for clarity later.
let x = CGFloat(arc4random_uniform(UInt32(self.gameView.bounds.size.width * 5))) - self.gameView.bounds.size.width * 2
let y = self.gameView.bounds.size.height
dropView.center = CGPointMake(x, -y)
在 Xcode 6 beta 3 中,必須將 arc4random_uniform UInt32 結果轉換為 CGFloat 才能使減法和乘法起作用.這不再起作用,編譯器顯示錯誤:
In Xcode 6 beta 3, it was necessary to cast the arc4random_uniform UInt32 result to CGFloat in order for the minus and multiplication to work. This doesn't work anymore and the compiler shows an error:
‘CGFloat’不能轉換為‘UInt8’
‘CGFloat’ is not convertible to ‘UInt8’
發行說明狀態:
CGFloat 現在是一種獨特的浮點類型,它在 32 位架構上封裝了 Float 或在 64 位架構上封裝了 Double.它提供了 Float 和 Double 的所有相同比較和算術運算,并且可以創建使用數字文字.使用 CGFloat 將您的代碼與您的代碼可能出現的情況隔離開來! 適用于 32 位,但在構建 64 位時失敗,反之亦然.(17224725)"
"CGFloat is now a distinct floating-point type that wraps either a Float on 32-bit architectures or a Double on 64-bit architectures. It provide all of the same comparison and arithmetic operations of Float and Double and may be created using numeric literals. Using CGFloat insulates your code from situations where your code would be !fine for 32-bit but fail when building for 64-bit or vice versa. (17224725)"
我只是在類型上做錯了嗎?我什至不知道如何更好地描述這個問題,以便向 Apple 提交 beta 4 的錯誤報告.我擁有的幾乎每個 Swift 項目都受到了這個問題的影響,所以我尋找一些理智.
Am I just doing something wrong with types? I don't even know how to describe this problem better to submit a bug report to Apple for beta 4. Pretty much every single Swift project I have that does any kind of point or rect manipulation got hit by this issue, so I'm looking for some sanity.
推薦答案
由于 Swift 沒有隱式類型轉換,您必須指定所有發生的類型轉換.讓這個案例特別乏味的是,目前 Swift 似乎缺乏 CGFloat
和 UInt32
等類型之間的直接轉換,你必須像你一樣通過一個中間類型發現了.
Since Swift doesn't have implicit type conversions, you must specify all the type conversions that take place. What makes this case particularly tedious, is that currently Swift seems to lack direct conversions between CGFloat
and types such as UInt32
, and you must go through an intermediate type as you've discovered.
最后,arc4random_uniform
需要進行兩次雙重轉換:
In the end, two double conversions are needed for the arc4random_uniform
:
let bounds = CGRectMake(0.0, 0.0, 500.0, 500.0)
var x = CGFloat(UInt(arc4random_uniform(UInt32(UInt(bounds.size.width) * 5))))
x -= bounds.size.width * 2
let center = CGPointMake(x, -bounds.size.height)
這篇關于'CGFloat' 不能轉換為 'UInt8' 和 Swift 和 Xcode 6 beta 4 的其他 CGFloat 問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!