swift code optimization and replaceSubrange issue

Greetings!

I'm new to swift programming and new to the Mac world. I developed programs for scientific computing in the past with FORTRAN, C++ and python but I'd like to learn swift because I think it is very flexible language. So here is my first program which is the solution of the linear convection using finite difference methods one of the fundamental equations in computational science. The array u could be velocity or temperature or something else and the u.replaceSubrange should apply initial conditions within a range in the u vector or 1D array. But this is wage since the size of u changes if I change the constant nx for example.
So here are the questions:
  1. Is there a better way working with replaceSubrange ?

  2. Is there a better way to write these lines in swift?

any comment or idea or suggestion is appreciated.

Thank you in advance!


Code Block
import Foundation
let nx: Int = 41
let nt: Int = 25
let dt: Double = 0.025
let c: Double = 1.0
var dx: Double
dx = 2.0 / Double(nx - 1)
var u: Array<Float> = Array(repeating: 1.0, count: nx)
var un = u
u.replaceSubrange(Int(0.5/dx)...Int(1/dx+1), with: repeatElement(2.0, count: 12))
for _ in 1...nt {
    un = u
    for i in 1..<nx {
        u[i] = un[i] - Float(c * dt / dx) * (un[i] - un[i-1])
    }
}
print(u)


Accepted Answer
I understand you want to keep the same number of elements in array u ?

So this writing is a bit risky (even though correct).
It would probably be safer to write

Code Block
for i in Int(0.5/dx)...Int(1/dx+1) { u[i] = 2.0 }

Otherwise I do not see problem, except that some var could have more explicit names (dx, dt, quite explicit, but nx and nt or u could be more explicit).

yes! Thank you.

by explicit do you mean something like this?

Code Block
var u: [Float]
u = Array(repeating: 1.0, count: nx)


Explicit, I mean a nam that will mean something later.

Could be
nx : numberOfPoints or numberOfMeasures
nt : numberIterations

However, if the var are very local to the computation func, not to be used elsewhere, a very short name, with a comment may be OK
var u: [Float] // The points of measure
Oh, yes! You're right. Bad old fortran habit. Well, thank you again!
swift code optimization and replaceSubrange issue
 
 
Q