I\'m trying to complete the exercise on page 46 of Apple\'s new book \"The Swift Programming Language\". It gives the following code:
func anyCommonElements
I had compiler errors with the above two solutions, I am running the guide from the iBook in the Xcode 6.01 playground. I had consistent compiler complaints about array declarations I found here so I am assuming the posters may be using an earlier version of swift. If I'm wrong, it would be great to know.
For array declarations, I have found that
var thingList : [ThingType] = []
has worked consistently, so I tended to go with that, forsaking
var thing[],thing[]() // gave compiler errors/warnings
My environment never was able to resolve a thing called T.GeneratorType[.Element]
The solution I came up for this experiment is
func anyCommonElements
(lhs: T, rhs: U)
-> [T.Generator.Element]
{
var returnValue: [T.Generator.Element] = []
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
returnValue.append(lhsItem)
}
}
}
return returnValue
}
let commonNumberList = anyCommonElements([1, 2, 3,4,5,6,7,8], [2,3,9,14,8,21])
println("common Numbers = \(commonNumberList)")
let commonStringList = anyCommonElements(["a","b","c"],["d","e","f","c","b"])
println("common Strings = \(commonStringList)")
The tutorial text really did not properly prepare me at all to actually solve the experiments without a lot of additional reading. Thanks to everyone here for contributing their solutions, it has really helped me get a great introduction to Swift.