swift - Array extension, Ambiguous reference to member 'subscript' -


i'm trying write extension array in xcode's playground. want write function modify array filled 0s when function called. code i'm attempting use this:

import foundation  extension array {     mutating func zero() {         in 0..<self.count {             self[i] = 0 // error - ambiguous reference member 'subscript'         }     } } 

this code not run, because of error at:

self[i] = 0 

however, if try 'get' value self, have no issues. example:

import foundation  extension array {     mutating func zero() {         in 0..<self.count {             print(self[i])         }     } } 

has no errors , runs expected.

so question is; why can't modify array?

also, replacing:

self[i] = 0 

with,

self.append(0) 

also results in error. (cannot invoke 'append' argument list of type '(int)')

so won't let me modify self @ seems.

it work if following:

extension array element: integerliteralconvertible {     mutating func zero() {         in 0..<self.count {             self[i] = 0         }     } } 

you must constrain type of elements allowed, because can't, example, 0 out array of strings.

it's important remember, when extending array, take account types of elements valid method you're adding. if requires elements of type, constrain on , work. way can use zero() method on arrays containing ints. might define different version array of strings replaces in array string "zero", example, , implementation used on type constrain well.


Comments