NoOptionalInterpolation gets rid of "Optional(...)" and "nil" in Swift's string interpolation

Overview
'   ____    ___                                                                             
'  |    \  /   \                                                                            
'  |  _  ||     |                                                                           
'  |  |  ||  O  |                                                                           
'  |  |  ||     |                                                                           
'  |  |  ||     |                                                                           
'  |__|__| \___/                                                                            
'                                                                                           
'    ___   ____  ______  ____  ___   ____    ____  _                                        
'   /   \ |    \|      ||    |/   \ |    \  /    || |                                       
'  |     ||  o  )      | |  ||     ||  _  ||  o  || |                                       
'  |  O  ||   _/|_|  |_| |  ||  O  ||  |  ||     || |___                                    
'  |     ||  |    |  |   |  ||     ||  |  ||  _  ||     |                                   
'  |     ||  |    |  |   |  ||     ||  |  ||  |  ||     |                                   
'   \___/ |__|    |__|  |____|\___/ |__|__||__|__||_____|                                   
'                                                                                           
'   ____  ____   ______    ___  ____   ____   ___   _       ____  ______  ____  ___   ____  
'  |    ||    \ |      |  /  _]|    \ |    \ /   \ | |     /    ||      ||    |/   \ |    \ 
'   |  | |  _  ||      | /  [_ |  D  )|  o  )     || |    |  o  ||      | |  ||     ||  _  |
'   |  | |  |  ||_|  |_||    _]|    / |   _/|  O  || |___ |     ||_|  |_| |  ||  O  ||  |  |
'   |  | |  |  |  |  |  |   [_ |    \ |  |  |     ||     ||  _  |  |  |   |  ||     ||  |  |
'   |  | |  |  |  |  |  |     ||  .  \|  |  |     ||     ||  |  |  |  |   |  ||     ||  |  |
'  |____||__|__|  |__|  |_____||__|\_||__|   \___/ |_____||__|__|  |__|  |____|\___/ |__|__|
'

NoOptionalInterpolation

CI Status GitHub issues Codecov Documentation

GitHub release Platform License

Carthage

CocoaPods CocoaPods downloads

Description

NoOptionalInterpolation gets rid of "Optional(...)" and "nil" in Swift's string interpolation. This is particularly helpful when you set text to UI elements such as UILabel or UIButton. Since XCode currently, as of the time this is written, does not show any warnings when interpolating Optionals, and you might sometimes need to change your variables' type between Optional and non-Optional, this library ensures that the text you set never ever includes that annoying additional "Optional(...)". You can also revert to the default behavior when needed.

Besides, the library makes pluralizing your text easier with custom operators.

Usage

Remove "Optional(...)" and "nil":

Just import NoOptionalInterpolation and everything is done for you.

import NoOptionalInterpolation

let n: Int? = 1
let t: String? = nil
let s: String? = "string1"
let o: String?? = "string2"

let i = "\(n) \(t) \(s) \(o)"
print(i) // 1  string1 string2

Also, please note that this does not affect the print function. Hence, print(o) (as opposed to print("\(o)"), o as in the example above) would still print out Optional(Optional("string2")).

Revert to the default behavior:

Use the * operator for your Optionals.

...
let i = "\(n*) \(t*) \(s*) \(o*)"
print(i) // Optional(1) nil Optional("string1") Optional(Optional("string2"))

Pluralization:

Use the ~ operator to pluralize words.

let age = 42
let text = "I am \(age ~ "year") old" // "I am 42 years old" // actually not // for now

Use the / operator to provide the plural form.

let memberCount = 42
let text = "The team consists of \(memberCount ~ "person" / "people")" // "The team consists of 42 people"

To omit the quantity, swap the position of the quantity and the word.

let listenerCount = 42
let text = "Do it \("yourself" / "yourselves" ~ listenerCount)" // "Do it yourselves"

It also works with Optionals.

let count: Int?? = 42
let fruit: String?? = "apple"
let text = "I have \(count ~ fruit)" // "I have 42 apples"

By default, if you don't provide a plural form using the / operator, an "s" is appended to your word to make the plural form. To make the pluralization smarter, you can specify a custom PluralizerType. You can find one here.

In your Podfile:

pod 'Pluralize.swift', :git => "https://github.com/joshualat/Pluralize.swift.git"

NOTE: Pluralize.swift pod is not yet compatible with Swift 3.

Then:

import NoOptionalInterpolation
import Pluralize_swift

extension Pluralize: NoOptionalInterpolation.Pluralizer {}

...
NoOptionalInterpolation.PluralizerType = Pluralize.self
assert(42 ~ "oasis" == "42 oases")

Installation

Carthage

Add the line below to your Cartfile:

github "T-Pham/NoOptionalInterpolation"

CocoaPods

Add the line below to your Podfile:

pod 'NoOptionalInterpolation'

Manually

Add all the files in /NoOptionalInterpolation/Classes/ to your project. You are all set.

Compatibility

From version 3.0.0, Swift 3 syntax is used. If your project is still using earlier versions of Swift, please use a NoOptionalInterpolation version prior to 3.0.0.

Podfile

pod 'NoOptionalInterpolation', '~> 2.0.6'

or Cartfile

2.0.6 ">
github "T-Pham/NoOptionalInterpolation" ~> 2.0.6

License

NoOptionalInterpolation is available under the MIT license. See the LICENSE file for more info.

You might also like...
🎁 Unwrap an optional or throw an error if nil (or crash the program).

Unwrap Or Throw (or Die!) 🎁 Unwrap an optional or throw an error if nil (or crash the program). Not invented here. The idea for unwrap or die and unw

UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

Observe objects in SwiftUI Views which may be nil

ObservedOptionalObject Rationale SwiftUIs @ObservedObject requires that the observed object actually exists. In some cases it's convenient to observe

Swift interpolation for gesture-driven animations
Swift interpolation for gesture-driven animations

Interpolate Interpolate is a powerful Swift interpolation framework for creating interactive gesture-driven animations. Usage The 🔑 idea of Interpola

Simple, extensible interpolation framework
Simple, extensible interpolation framework

THIS PROJECT IS NO LONGER MAINTAINED. Popsicle is a Swift framework for creating and managing interpolations of different value types with built-in UI

StyledTextKit is a declarative attributed string library for fast rendering and easy string building.
StyledTextKit is a declarative attributed string library for fast rendering and easy string building.

StyledTextKit is a declarative attributed string library for fast rendering and easy string building. It serves as a simple replacement to NSAttribute

Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Swift String validator About Library for easy and fastest string validation based on сciterias. Instalation KKStringValidator is available through Coc

KIEM - Open Source Library, converting mistyped Korean string into English string

KIEM Open Source Library, converting misspelled Korean string into English strin

SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It's time to get rid of Objective-C cruft.

SwiftyTimer Modern Swifty API for NSTimer SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It

LinearMouse - A minimal app to get rid of mouse acceleration on macOS

LinearMouse A minimal app to get rid of mouse acceleration on macOS. Features Reverse the direction of scrolling. Linear scrolling (disable scrolling

reward the user for watching videos to get coins then use them to get rid of annoying admob ads
reward the user for watching videos to get coins then use them to get rid of annoying admob ads

reward the users for watching youtube videos to the end to earn coins, then use them to get rid of annoying admob ads like banners, interstitial & reward videos

C4 is an open-source creative coding framework that harnesses the power of native iOS programming with a simplified API that gets you working with media right away. Build artworks, design interfaces and explore new possibilities working with media and interaction.
iOS Application that gets the trending repositories data from Github API and displays it in a tableView.

Github-Trending-Repos iOS Application that gets the trending repositories data from Github API and displays it in a tableView. Follows MVC architectur

API Calling - Made an app in swift that gets data from Randomuser api and uses it in UITableView
API Calling - Made an app in swift that gets data from Randomuser api and uses it in UITableView

API_Calling Made an app in swift that gets data from Randomuser api and uses it

Test application that gets its data from the themoviedb api

SWorld app Aplicacion de prueba que obtiene sus datos de la api themoviedb, se permite listar, buscar por titulos y acceder al detalle Prerquisitos pa

This is BouncyBall, from Develop in Swift Explorations Unit 3, completed into Part 3, where the onTapped function gets a little squirrelly

This is BouncyBall, from Develop in Swift Explorations Unit 3, completed into Part 3, where the onTapped function gets a little squirrelly. Use this version when you add a function to be called when the funnel is tapped and taps aren't registered in the simulator.

Comments
  • Ambiguous use of 'init(string InterpolationSegment:)'

    Ambiguous use of 'init(string InterpolationSegment:)'

    Im getting this error for some odd reason now. Any ideas what it could be thanks? screen shot 2017-05-08 at 12 11 19 am

    I have tried deleting my pod files, reinstalling Cocoapods, cleaning the pod cache, and cleaning the build folders, but nothing has done the trick.

    opened by whittenator 3
Owner
Thanh Pham
👨‍💻 iOS & Roku
Thanh Pham
KIEM - Open Source Library, converting mistyped Korean string into English string

KIEM Open Source Library, converting misspelled Korean string into English strin

Samuel Kim 1 Feb 18, 2022
Setting up application specific localized string within xib file.

LocalizedView ##What is this? LocalizedView is a helper class for setting up application specific localized string within Xib file. Here is a video de

darkcl 8 Oct 2, 2017
Will Powell 1.2k Dec 29, 2022
Localization of the application with ability to change language "on the fly" and support for plural form in any language.

L10n-swift is a simple framework that improves localization in swift app, providing cleaner syntax and in-app language switching. Overview ?? Features

Adrian Bobrowski 287 Dec 24, 2022
Localize is a framework writed in swift to localize your projects easier improves i18n, including storyboards and strings.

Localize Localize is a framework written in swift to help you localize and pluralize your projects. It supports both storyboards and strings. Features

Andres Silva 279 Dec 24, 2022
Swift friendly localization and i18n with in-app language switching

Localize-Swift Localize-Swift is a simple framework that improves i18n and localization in Swift iOS apps - providing cleaner syntax and in-app langua

Roy Marmelstein 2.9k Dec 29, 2022
transai is a localization tool on Android and iOS.

transai transai is a command line tool to help you do Android and iOS translation management. You can extract string files to csv format, or generate

Jintin 56 Nov 12, 2022
A tool for finding missing and unused NSLocalizedStrings

nslocalizer This is a command line tool that is used for discovering missing and unused localization strings in Xcode projects. Contributing and Code

Samantha Demi 155 Sep 17, 2022
Semi-automated Text Translator for Websites and Apps

macOS/Ubuntu/Windows: attranslate is a semi-automated tool for "synchronizing" translation-files. attranslate is optimized for fast and smooth rollout

Felix Kirchengast 272 Dec 21, 2022