Use a function to find common elements in two sequences in Swift

前端 未结 8 796
时光说笑
时光说笑 2020-12-30 00:07

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         


        
8条回答
  •  孤城傲影
    2020-12-30 00:47

    The problem was to define the return value as an array so that was possible to add element to it.

    func anyCommonElements(lhs: T, rhs: U) -> Array  {
       var result = Array ();
       for lhsItem in lhs {
           for rhsItem in rhs {
              if lhsItem == rhsItem {
                result.append(lhsItem);
              }
           }
      }
      return result;
    }
    
    print(anyCommonElements([1,3,7,9,6,8],rhs:[4,6,8]));
    

提交回复
热议问题