Search code examples
rangeswift3function-parameter

Swift 3.0 range as function parameter


I'm making a function to get the specific days that falls on specific weekdays

Ex. Sundays in 9.2016 = 4,11,18,25

import UIKit

var daysOff = [Int]()

func getNumberOfDaysInMonth (_ month : Int , _ Year : Int ,lookingFor : Int) -> (firstDay: Int , daysResults: [Int]) {
var day = Int()


if lookingFor > 7 || lookingFor < 1 {
    print("error")
   return (0,[0])
}else {
    day = lookingFor
}

let dateComponents = NSDateComponents()
dateComponents.year = Year
dateComponents.month = month
let calendar = Calendar(identifier: .gregorian)
let date = calendar.date(from: dateComponents as DateComponents)!


let range = calendar.range(of: .day, in: .month, for: date)

let maxDay = range?.count

let dow = calendar.component(.weekday, from: date)

var firstday = 0
switch dow  {
case let x where x > day:
    let a = 8 - dow
    firstday = a + day
case let x where x < day:
    let a = day - dow
    firstday = a + 1
case let x where x == day:
    firstday = dow
    default:
    print("error")
}
switch firstday {
case 1:
    print("1")
    if maxDay! > 29 {
        daysOff = [1,8,15,22,29]
    } else {
        daysOff = [1,8,15,22]
    }
case 2:
    print("2")
    if maxDay! > 30 {
        daysOff = [2,9,16,23,30]
    }else {
        daysOff = [2,9,16,23]
    }
case 3:
    print("3")
    if maxDay! == 31 {
        daysOff = [3,10,17,24,31]
    }else {
        daysOff = [3,10,17,24]
    }
case 4:
    print("4")
    daysOff = [4,11,18,25]
case 5:
    print("5")
    daysOff = [5,12,19,26]
case 6:
    print("6")
    daysOff = [6,13,20,27]
case 7:
    print("7")
    daysOff = [7,14,21,28]

default:
    print("something went wrong")
}
return (firstday,daysOff)
}
let test = getNumberOfDaysInMonth(9,2016,lookingFor: 7)
test.daysResults
test.firstDay

I wanna make sure that the lookingFor parameter gets a number from 1 to 7

Can i specify a range to a parameter?! Do i need a guard statement?!


Solution

  • I don't think there is any way to verify the parameter that is not just a simple check in the function, using the pattern match operator and a guard statment:

    var lookingForRange = 1...7
    func foo(lookingFor: Int){
        guard lookingForRange ~= lookingFor else{
            //handle out of range
            print("out of range")
            return
        }
    }
    
    //prints out of range
    foo(lookingFor: 8)
    

    More detailed answer on pattern matching: Can I use the range operator with if statement in Swift?