Write a += 8 instead of complicated thing

Hi, I was just using the swift playground, and I would like to ask if there is a way to write this line shorter:

a = (a as! Int + 8) as! T

in here:

import Foundation

func test() {

    func blah<T>(a: inout T) {

        switch a {
            case is Int:
                a = (a as! Int + 8) as! T

                // want to write something like    a += 8
                // because it is in the Int case so the compiler should know...

            default: break
        }
    }

    var xx : Int = 5
    blah(a: &xx)

    print(xx)
}

test()

I guess what you need is something like (partial) specialization in C++. Swift does not have this feature, but I think “overload” may help you.

func blah(a: inout Int) {
    a += 8
}
func blah<T>(a: inout T) {
}

var number: Int = 5
blah(a: &number)

print(number) // Print "13"
1 Like

Another (slightly less verbose) approach:

switch a {
case let tmp as Int:
  a = (tmp + 8) as! T
default: break
}

Are you sure you want it to work specifically and only with Int? All you're assuming is that T is ExpressibleByIntegerLiteral, and that it uses +, so you could easily support Int32, UInt8, etc:

func blah<T: Numeric>(a: inout T) {
  a += 8
}
func test() {
  var xx = 5
  blah(a: &xx)
    
  print(xx) // 13
}

test()
3 Likes

Actually I had planned to use nested functions, where Swift does not allow me to overload functions.

I want the blah() to modify some counter outside. I could do it with only global functions like you wrote, but my counter would have to be global too, and then would need to reset it before each call to test().

PS: But maybe I can use globals. Good to be reminded globals can be overloaded. Anyway thanks. :slight_smile:

I want to port some Golang code to Swift and keep it Golang-idiomatic, so who knows. :)

This is a bit shorter, thanks.

Good to know about Numeric.