要使用参数调用函数,需要在Swift 3.0中一起编写每个参数。 但是一旦使用类型注释将函数赋值为常量,则无需编写每个参数。为什么?
func foo(base : Int) {
print ("param = \(base)")
}
// Case 1
let s : (Int) -> () = foo
s(5) // SUCCESS!
s(base:5) // Error!
// Case 2
let k : (base: Int) -> () = foo
k(5) // Error!
k(base: 5) // SUCCESS!
// Case 3
let t = foo
t(5) // Error!
t(base: 5) // SUCCESS!
答案 0 :(得分:1)
因为您可以将更具体的对象分配给更通用类型的变量(例如,子类对象为超类变量,但我们不是在这里讨论类),但反之亦然。
(base: Int) -> ()
是一般(Int) -> ()
函数的更具体的情况。因此,任何(base: Int) -> ()
都是(Int) -> ()
函数,但任何(Int) -> ()
函数都不是(base: Int) -> ()
函数。
之后,当您使用您创建的变量时,Swift会根据其类型对其进行处理。如果是(base: Int) -> ()
,那么参数名称是必需的,否则它不是必需的。
因此,在第一种情况下,您将变量显式声明为(Int) -> ()
并相应地使用它。斯威夫特没有对这些方面做出任何假设:
s(5) // SUCCESS!
s(base:5) // Error!
它只知道变量的类型为(Int) -> ()
。它可以是任何其他(Int) -> ()
函数,例如(whatever: Int) -> ()
。
在第二种情况下,变量显式创建为(base: Int) -> ()
,因此要使用它,应指定名称。
在第三种情况下,变量隐式创建为(base: Int) -> ()
(Swift自动推断出类型)。
答案 1 :(得分:0)
{
let location : NSString = Txtsrch.text! as NSString
let geocoder : CLGeocoder = CLGeocoder()
geocoder.geocodeAddressString(location as String, completionHandler: {(placemarks, error) -> Void in
if((error) != nil){
print("Error", error)
let alert = UIAlertController(title: "Search Invelid", message: "Please Enter Valid Place", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else
{
if let placemark = placemarks?.first {
let coordinates : CLLocationCoordinate2D = placemark.location!.coordinate
}
if (placemarks!.count > 0) {
print(placemarks![0])
let topResult : CLPlacemark = placemarks![0]
let placemark: MKPlacemark = MKPlacemark(placemark: topResult);
self.lat = (placemark.location?.coordinate.latitude)!
self.lng = (placemark.location?.coordinate.longitude)!
print("coordinate=",placemark.location?.coordinate.latitude)
var region: MKCoordinateRegion = self.mapli!.region;
region.center = (placemark.location?.coordinate)!;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
self.mapli!.setRegion(region, animated: true);
self.mapli!.addAnnotation(placemark);
self.bool = true
}
}
})
}
答案 2 :(得分:-2)
当你做“速记”时,你正在创建一个“s”,它是一个泛型类型,满足签名要求,即输入参数类型为Int且没有返回值。
当你将foo分配给该常量时,你符合类型要求,而foo现在在s里面“嵌套”。
也许......