C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We can pass many types of objects to print(), such as Strings and Ints. For clear code, it is best not to convert to a string.
Print: In Swift 3, this adds a newline after the argument. We can specify a separator and terminator.
Interpolation: We can use the string interpolation syntax to write more complex data. We use an escaped parenthesis syntax.
Swift program that uses print
// Call print with strings.
// ... No newline is inserted.
print("one ")
print("two ")
// An Int can be printed.
print(3)
// Print can handle multiple arguments.
// ... Specify a separator and a terminator.
print("cat", "dog", "bird",
separator: ";",
terminator: ".\n")
// Print a bool.
print(true)
Output
one
two
3
cat;dog;bird.
true
Here: We loop over the characters in an array. We then print them all on the same line, with no separating newlines.
Swift program that uses print, empty terminator
var letters: [Character] = ["a", "b", "c", "d"]
// Loop over characters in array.
for c in letters {
// Print with no terminator.
print(c, terminator: "")
}
Output
abcd
Tip: We use escaped parentheses to begin variable lookups in a string interpolation. Here we separate two values with a ":" character.
Swift program that uses print, string interpolation
var number = 10
var title = "The Sound and the Fury"
// Print with format string.
// ... String interpolation inserts both variables.
print("\(number): \(title)")
Output
10: The Sound and the Fury
Here: The Box class inherits from CustomStringConvertible and we provide a description. Print uses the description to write to the screen.
Caution: The description for Box is not a good example—it should include fields. But it shows how the property works.
Swift program that uses print, CustomStringConvertible
class Box: CustomStringConvertible {
var description: String {
// Return a string that represents this instance.
return "Box string representation"
}
}
// Create new instance of class.
let b = Box()
// Print with CustomStringConvertible.
print(b)
Output
Box string representation