Local var in GeometryReader

GeometryReader { geometry in
    let len = geometry.size.width * 0.4

    Path { path in
        ...
    }
}

breaks the compiler in Xcode 11 beta 4. Without line 2 it passes compilation. Is it not permitted to declare local contants and variables in GeometryReader?

Accepted Reply

There are two ways to fix this

First, move local contants and variables inside Path closure

GeometryReader { geometry in
    Path { path in
        let width = geometry.size.width
        let height = geometry.size.height
        
        path.move(
            to: CGPoint(
                x: 0,
                y: 0
            )
        )
        
        path.addLine(
            to: CGPoint(
                x: width,
                y: height
            )
        )
    }
    .stroke(Color.black)
}


Second, define return type of GeometryReader closure

GeometryReader { geometry -> ShapeView<StrokedShape<Path>, Color> in
    let width = geometry.size.width
    let height = geometry.size.height
    
    return Path { path in
        path.move(
            to: CGPoint(
                x: 0,
                y: 0
            )
        )
        
        path.addLine(
            to: CGPoint(
                x: width,
                y: height
            )
        )
    }
    .stroke(Color.black)
}

Replies

There are two ways to fix this

First, move local contants and variables inside Path closure

GeometryReader { geometry in
    Path { path in
        let width = geometry.size.width
        let height = geometry.size.height
        
        path.move(
            to: CGPoint(
                x: 0,
                y: 0
            )
        )
        
        path.addLine(
            to: CGPoint(
                x: width,
                y: height
            )
        )
    }
    .stroke(Color.black)
}


Second, define return type of GeometryReader closure

GeometryReader { geometry -> ShapeView<StrokedShape<Path>, Color> in
    let width = geometry.size.width
    let height = geometry.size.height
    
    return Path { path in
        path.move(
            to: CGPoint(
                x: 0,
                y: 0
            )
        )
        
        path.addLine(
            to: CGPoint(
                x: width,
                y: height
            )
        )
    }
    .stroke(Color.black)
}