BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Fixing "Ambiguous reference to member when using ceil or round"

Swift version: 5.6

Paul Hudson    @twostraws   

If you've ever come across the error message "No 'ceil' candidates produce the expected contextual result type 'Int'" – which can happen with calls to ceil(), floor(), and round() – it's usually down to Swift being unable to satisfy type requirements you have asked for.

Put simply, you might think calling ceil() rounds a floating-point number up to its nearest integer, but actually it doesn't return an integer at all: if you give it a Float it returns a Float, and if you give it a Double it returns a Double.

So, this code works because c ends up being a Double:

let a = 0.5
let c = ceil(a)

…whereas this code causes your exact issue because it tries to force a Double into an Int without a typecast:

let c: Int = ceil(a)

If you need c to be an integer, the solution is to convert the return value of ceil() to be an integer, like this:

let c = Int(ceil(a))

The same is true of the floor() and round() functions, so you'd need the same solution.

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.