Ios8 在swift2中使用self
我尝试用swift 2编写以下代码:Ios8 在swift2中使用self,ios8,swift2,Ios8,Swift2,我尝试用swift 2编写以下代码: //: Playground - noun: a place where people can play import Foundation struct Point { var x: Double var y: Double } func distanceTo (#point: Point) -> Double { let a = abs(self.x - point.x) let b = abs(self.y - point.y) le
//: Playground - noun: a place where people can play
import Foundation
struct Point {
var x: Double
var y: Double
}
func distanceTo (#point: Point) -> Double {
let a = abs(self.x - point.x)
let b = abs(self.y - point.y)
let c = sqrt(a * a + b * b)
return c
}
let pointA = Point(x: 1.0, y: 2.0)
let pointB = Point(x: 4.0, y: 6.0)
let distance = pointA.distanceTo (point: pointB)
但我有一个错误:
#has been remove from swift, so i change the code to
func distanceTo (#point: Point) -> Double
但后来我又犯了一个错误:
use of unresolved identifier 'self'
有没有关于如何在swift 2中修复此错误的线索
thanx您需要将distanceTo作为点结构的成员-请参阅:
import Foundation
struct Point {
var x: Double
var y: Double
func distanceTo (point point: Point) -> Double {
let a = abs(self.x - point.x)
let b = abs(self.y - point.y)
let c = sqrt(a * a + b * b)
return c
}
}
let pointA = Point(x: 1.0, y: 2.0)
let pointB = Point(x: 4.0, y: 6.0)
let distance = pointA.distanceTo (point: pointB)
我认为您打算将
distance设置为Point
的成员,因此必须将其放入struct
定义中。否则它将不知道self
指的是什么:
struct Point {
var x: Double
var y: Double
func distanceTo (point point: Point) -> Double {
let a = abs(self.x - point.x)
let b = abs(self.y - point.y)
let c = sqrt(a * a + b * b)
return c
}
}
let pointA = Point(x: 1.0, y: 2.0)
let pointB = Point(x: 4.0, y: 6.0)
let distance = pointA.distanceTo (point: pointB)
顺便说一句,您不需要点:
,通常会将其合并到方法名称中:
struct Point {
var x: Double
var y: Double
func distanceToPoint(point: Point) -> Double {
let a = abs(self.x - point.x)
let b = abs(self.y - point.y)
let c = sqrt(a * a + b * b)
return c
}
}
let pointA = Point(x: 1.0, y: 2.0)
let pointB = Point(x: 4.0, y: 6.0)
let distance = pointA.distanceToPoint(pointB)
仅供参考,您也可以使用hypot(a,b)
,而不是sqrt(a*a+b*b)
。thax alot Shripada:)是的,Thanx您罗布,我是新来的,尝试探索该功能以及如何正确使用它,Thanx谢谢您的帮助。