Private var is accessible from outside the class

Access modifiers in Swift are implemented differently than other languages. There are three levels: private: accessible only within that particular file internal: accessible only within the module (project) public: accessible from anywhere Unless marked otherwise, everything you write is internal by default. The Swift blog had a post about access control when the features were … Read more

Initializer for conditional binding must have Optional type, not ‘String’

The compiler is telling you that you can’t use an if let because it’s totally unnecessary. You don’t have any optionals to unwrap: URL is not optional, and the absoluteString property isn’t optional either. if let is used exclusively to unwrap optionals. If you want to create a new constant named url, just do it: … Read more

How to convert a binary to decimal in Swift?

Update for Swift 2: All integer types have an public init?(_ text: String, radix: Int = default) method now, which converts a string to an integer according to a given base: let binary = “11001” if let number = Int(binary, radix: 2) { print(number) // Output: 25 } (Previous answer:) You can simply use the … Read more

How to split a string into substrings of equal length

I just answered a similar question on SO and thought I can provide a more concise solution: Swift 2 func split(str: String, _ count: Int) -> [String] { return 0.stride(to: str.characters.count, by: count).map { i -> String in let startIndex = str.startIndex.advancedBy(i) let endIndex = startIndex.advancedBy(count, limit: str.endIndex) return str[startIndex..<endIndex] } } Swift 3 func … Read more

tech