Explicitly specify generic type constraint when calling function

时间:2016-02-12 21:20:53

标签: ios swift generics

I am wondering wether or not is possible in private void cmd_SelectAll_Click(object sender, RoutedEventArgs e) { foreach (object o in TransformerList.Items) { TransformerList.SelectedItems.Add(o); //I have also tried TransformerList.SelectAll(); } } to explicitly specify the generic type of a generic function. Assuming I have the following function definition which basically creates an empty array of a generic type Swift:

T

How would I be able to call it?

func bar<T>() -> [T] {
    return [T]()
}

results in

generic parameter 'T' could not be inferred

which makes total sense since there really is no information to infer anything here.

But unfortunately my attempt at specifying the type constraint explicitly via the following failed as well:

var foo = bar()

error: cannot explicitly specialize a generic function

  • Why am I not able to do that?
  • Is it a language specification to not be able to explicitly specify the generic type?
  • What way is there to specify the generic type of the function?

2 个答案:

答案 0 :(得分:5)

What way is there to specify the generic type of the function?

The generic type can be inferred from the context:

package drawAPI {
   use MooseX::Interface;
   require 'draw';
   one;
}

package shape {
   use MooseX::ABC;
   with 'drawAPI';
}

package square {
   extends 'shape';
    #here is where having a draw subroutine would be inforced
   sub draw {};
}

(I cannot answer the other questions.)

答案 1 :(得分:3)

The language doesn't allow you to explicitly specialize the function. I don't know why they implemented it that way. You're more likely to get an answer to that question on the swift-users mailing list.

The typical way to fix this is to make the function take the type as an argument:

$re = "/((\\\"[\\s\\S]+?\\\")|[\\s\\S]+?(:(?2))?)\\K(\\s+|$)/"; 
$str = "1/2 one two \"three & four\" five:six seven:\"eight nine ten\""; 
$subst = "\r\n"; 

$result = preg_replace($re, $subst, $str);