How to read swift headers -


when cmd click split function in xcode, takes me header file. reads

public func split(maxsplit: int = default, allowemptyslices: bool = default, @noescape isseparator: (self.generator.element) throws -> bool) rethrows -> [self.subsequence] 

how following implementation work above declaration?

somestring.characters.split { $0 == "." } 

let's break down:

public func split(maxsplit: int = default, allowemptyslices: bool = default, @noescape isseparator: (self.generator.element) throws -> bool) rethrows -> [self.subsequence] 

maxsplit: first parameter, maxsplit, allows specify maximum number of pieces sequence split into. default int.max.

allowemptyslices: second parameter, allowemptyslices specifies whether or not 2 consecutive separators in sequence should lead empty slice. default false. example if had string, "a..b", , split on . character, end either 2 (["a", "b"]) or 3 (["a", "", "b"]) items in output array depending on pass parameter.

isseparator: last parameter closure pass identify split sequence.

since both maxsplit , allowemptyslices have default arguments, don't need include them in function call unless want change them. parameter have supply isseparator closure.

in case, called:

somestring.characters.split { $0 == "."} 

...which equivalent of:

somestring.characters.split(maxsplit: int.max, allowemptyslices: false) { $0 == ".' } 

you write function call this:

somestring.characters.split(isseparator: { $0 == "." }) 

the way have written makes use of "trailing closure" syntax. if function takes closure it's final argument, can move closure outside parentheses this:

somestring.characters.split() { $0 == "." } 

and if function takes only 1 argument (not counting default arguments not supplying) can omit parentheses altogether:

somestring.characters.split { $0 == "." } 

at highest level, happens split iterates through sequence of characters. tests each character using supplied closure, , if closure returns true, splits sequence on character. in case split sequence of characters every time locates ".".

some other notes:

rethrows: whole function marked rethrows. throw error, if closure pass isseparator argument throws error itself. note isseparator parameter allows pass closure throws error, don't have to. time function accepts closure throws error, accept closure not throw. because non-throwing functions sub-type of throwing functions.

@noescape: isseparator parameter marked @noescape. means nothing in closure survive past end of call split.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -