2016-06-02 7 views
0

속성과 비슷한 함수 매개 변수를 사용하여 inout을 사용할 수 있습니까? 속성 자체는 변경하고 속성은 변경하지 않으려고합니까?const 속성의 Swift inout 매개 변수

let someLine = CAShapeLayer() 

func setupLine(inout line:CAShapeLayer, startingPath: CGPath) { 
    line.path = startingPath 
    line.strokeColor = UIColor.whiteColor().CGColor 
    line.fillColor = nil 
    line.lineWidth = 1 
} 

setupLine(&someLine, startingPath: somePath) 

그들도 도움이 될 것입니다 루프하지 않을 때는 같은 방법으로 속성의 무리를 설정하는 더 나은 방법이 또한합니다.

+0

당신은 모든 여기 inout' – Alexander

답변

3

CAShapeLayer클래스하고 따라서 참조 형이다.

let someLine = CAShapeLayer() 

CAShapeLayer 개체에 대한 상수입니다. 이 참조를 함수 에 전달하고 함수 내에서 참조 된 개체의 속성을 수정할 수 있습니다.

func setupLine(line: CAShapeLayer, startingPath: CGPath) { 
    line.path = startingPath 
    line.strokeColor = UIColor.whiteColor().CGColor 
    line.fillColor = nil 
    line.lineWidth = 1 
} 

let someLine = CAShapeLayer() 
setupLine(someLine, startingPath: somePath) 

가능한 대안 레이어

let someLine = CAShapeLayer(lineWithPath: somePath) 

으로 생성 될 수있는 편의 이니셜 그래서

extension CAShapeLayer { 
    convenience init(lineWithPath path: CGPath) { 
     self.init() 
     self.path = path 
     self.strokeColor = UIColor.whiteColor().CGColor 
     self.fillColor = nil 
     self.lineWidth = 1 
    } 
} 

은 다음 & 운영자 또는 inout 필요 없다

놀이터를위한 완벽한 예. 기본값으로

import UIKit 

class ShapedView: UIView{ 
    override var layer: CALayer { 
     let path = UIBezierPath(ovalInRect:CGRect(x:0, y:0, width: self.frame.width, height: self.frame.height)).CGPath 
     return CAShapeLayer(lineWithPath: path) 
    } 
} 

extension CAShapeLayer { 
    convenience init(lineWithPath path: CGPath, strokeColor:UIColor? = .whiteColor(), fillColor:UIColor? = nil, lineWidth:CGFloat = 1) { 
     self.init() 
     self.path = path 
     if let strokeColor = strokeColor { self.strokeColor = strokeColor.CGColor } else {self.strokeColor = nil} 
     if let fillColor = fillColor { self.fillColor = fillColor.CGColor } else {self.fillColor = nil} 
     self.lineWidth  = lineWidth 
    } 
} 


let view = ShapedView(frame: CGRect(x:0, y:0, width: 100, height: 100)) 

결과 : 그것이 더 다양한 있도록 기본 매개 변수를 사용합니다

screenshot

+0

너무 감사합니다'필요가없는, 완전히 읽기 워드 프로세서 : 클래스 '인스턴스'는 참조 유형이고, 함수는 참조 유형이며, 그 밖의 모든 것은 값 유형입니다. 대안을 가져 주셔서 감사합니다! – richy

+0

다음은 메서드 매개 변수의 기본값을 사용하는 방법을 보여주는 완벽한 예입니다. https://gitlab.com/snippets/20356 @Martin R : 원할 경우이 코드를 자유롭게 답변에 추가하십시오. – vikingosegundo

+0

@vikingosegundo : 좋은 제안, 고마움,하지만 오늘 너무 늦었습니다.이 하나를 편집하거나 직접 답변을 추가하십시오! –