Skip to content

Swift makes read-write object references read only #247

Description

@mittelmark

Here is my code which works fine in C, C++, C#, D, Java, Js, Py and Ts, but not in Swift:

 public static class Values {
         public static void AddValues (int n, List<float>! values) {
                 for (int i = 0; i < n; i++) {
                         float f = i*1.0;
                         values.Add(f);
                 }
         }
         public static void Main () {
                 List<float>() values;
                 AddValues(5,values);
                 AddValues(6,values);
                 Console.WriteLine($"Count: {values.Count}");
                 
         }
 }

In Swift the values argument becomes immutable:

// Generated automatically with "fut". Do not edit.

public class Values
{

        public static func addValues(_ n: Int, _ values: [Float])
        {
                for i in 0..<n {
                        let f: Float = Float(Double(i) * 1.0)
                        values.append(f)
                }
        }

        public static func main()
        {
                var values = [Float]()
                Values.addValues(5, values)
                Values.addValues(6, values)
                print("Count: \(values.count)")
        }
}

Values.main()

Which then leads to an error:

 8 |            for i in 0..<n {
 9 |                    let f: Float = Float(Double(i) * 1.0)
10 |                    values.append(f)
   |           `- error: cannot use mutating member on immutable value: 'values' is a 'let' constant
11 |            }

The suggested fix is to make the argument inout and adding a reference & in the call line:

 public static func addValues(_ n: Int, _ values: inout [Float]) {
        for i in 0..<n {
            let f: Float = Float(Double(i) * 1.0)
            values.append(f)
        }
    }
	public static func main()
	{
		var values = [Float]()
		Values.addValues(5, &values)
		Values.addValues(6, &values)
		print("Count: \(values.count)")
	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions