3

Relatively new to Swift and struggling with the simplest of things. I wish to preallocate an array of structs set to default values. This works just as long as the struct is not nested inside another type. Any ideas? Here is simplified example:

struct PlainStruct
{
    var yo:Float = 0.0
}

class WrapperClass
{
    struct NestedStruct
    {
        var yo:Float = 0.0
    }
}

// Works just fine
var a = [PlainStruct](count:2, repeatedValue:PlainStruct())

// Error - Cannot call value of non-function type '[WrapperClass.NestedStruct.Type]'
var b = [WrapperClass.NestedStruct](count:2, repeatedValue:WrapperClass.NestedStruct())

Thanks

2
  • It seems to be a compiler bug: stackoverflow.com/questions/25682113/… Commented Nov 19, 2015 at 12:27
  • Hi, yeah good point, but in this case I actually do want a Float and without that I believe it defaults to a Double. Thanks Commented Nov 19, 2015 at 12:28

1 Answer 1

4

It works if you create a typealias. Example:

struct PlainStruct
{
    var yo:Float = 0.0
}

class WrapperClass
{
    struct NestedStruct
    {
        var yo:Float = 0.0
    }
}

typealias Nested = WrapperClass.NestedStruct

var b = [Nested](count:2, repeatedValue:WrapperClass.NestedStruct())

As for why we have to do this... I don't like to say this without proof but I think it's a compiler bug, I believe we should be able to use your original version.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice, didn't know about type alias. That does work so will go with that until the bug in the compiler is addressed. Thanks!
Problem still appears in Swift 3.0.2. Array<WrapperClass.NestedStruct>(repeating: ..., count: ...) works around the problem as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.