Does Swift support implicit conversion?

后端 未结 3 625
囚心锁ツ
囚心锁ツ 2020-11-30 05:31

For example, I have the following code:

    let numberOfBlocks = 3
    let blockWidth = SKSpriteNode(imageNamed: \"image.png\").size.width
    let padding =          


        
3条回答
  •  温柔的废话
    2020-11-30 06:05

    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.

提交回复
热议问题