How to initialize Swift array with nil -
i trying have nil
zeroth index element , rest have value of generic type t
comparable
.
so when initialise nil
works expected
struct container<t: comparable> { var container = [t?]() init() { container.append(nil) } }
but when integer 0, ambiguous reference
struct container<t: comparable> { var container = [t?]() init() { container.append(0) } } playground execution failed: error: algorithms.playground:7:9: error: ambiguous reference member 'append' container.append(0) ^~~~~~~~~
i want understand why error occurring?
t
can any comparable type (string
, custom type, ...), , initializing 0
not possible.
you require t
can created integer literal, covers integer , floating point types:
struct container<t: comparable> t: expressiblebyintegerliteral { var container = [t?]() init() { container.append(0) } }
or provide separate append()
method:
struct container<t: comparable> { var container = [t?]() init() { container.append(nil) } mutating func append(_ newelement: t) { container.append(newelement) } } var c = container<int>() c.append(0)
Comments
Post a Comment