본문 바로가기
개발/iOS

Swift ] Swift로 콘솔 출력 해보기 print

by lucidmaj7 2019. 11. 17.
728x90
반응형

프로그래밍언어를 처음 배우면 가장 먼저 하는 것은 바로 hello world! 출력하기 일 것 이다. 출력은 프로그램의 결과물이며 프로그래머가 작성한 프로그램이 올바르게 동작했는지 확인하는 가장 확실한 방법이기 때문이다.

 

printf("hello world\n");

console.log("hello world");

System.out.print("hello world");

print "hello world"

echo "hello world"

....

 

 

 

Swift를 배우는 첫걸음으로 콘솔 출력을 해보자. 다른 언어와 같이 콘솔 출력은 간단한 함수 하나로 시작된다.

 

print

https://developer.apple.com/documentation/swift/1541053-print

 

print(_:separator:terminator:) - Swift Standard Library | Apple Developer Documentation

Function print(_:separator:terminator:) Writes the textual representations of the given items into the standard output. Declarationfunc print(_ items: Any..., separator: String = " ", terminator: String = "\n") ParametersitemsZero or more items to print.se

developer.apple.com

Swift 이전 Objective C에서는 주로 NSLog함수를 통해 콘솔에 출력하였다.

 

swift에서는 print함수를 통해 아래 와 같이 출력한다.

 

import Cocoa

var str = "Hello, playgroundwww"

print("hello " + str)
print("hello \(str)") //변수 바인딩

//상수 선언
let a : Int = 5
let b : Int = 6

print("a는 \(a)")  //상수 출력
print("b는 \(b)")
print("a+b 는 \(a+b)")   //연산식 출력

 

print함수는 변수를 인자로 받는다. 인자로 전달된 변수를 콘솔에 출력하여 준다. 이때 여러가지 방법의 조합으로 출력이 가능하다. 문자열 사이에 \(변수)를 이용해 문자열을 바로 바인딩하여 출력이 가능하다. 또한 이를 통해 연산식도 바로 출력이 가능하다.

 

출력 결과

 

하지만 무언가 이상하지 않은가? 우리는 newline(\n)을 입력하지 않았음에도 불구하고 newline이 입력되여 각각 한줄 한줄 출력되고 있다. 그 이유는 print함수의 원형에서 찾을 수 있었다.

 

https://developer.apple.com/documentation/swift/1541053-print

 

Apple의 개발자 문서에서 print함수는 단순히 하나의 인자만 받는게 아니라 여러가지 인자를 받을 수 있는데 기본으로 입력되는 terminator 인자에 \n이 기본으로 할당되어 있다. 이 때문에 terminator를 지정하지 않을 때 자동으로 newline을 출력해 주는 것이다. 그렇다면 newline을 빼고 출력해보자.

 

아래와 같이 terminator에 ""빈 문자열을 입력하여 주면 개행문자가 출력되지 않아 한 줄로 출력됨을 볼 수 있다.

import Cocoa

var str = "Hello, playgroundwww"

print("hello " + str, terminator:"")
print("hello \(str)", terminator:"")
let a : Int = 5
let b : Int = 6

print("a는 \(a)", terminator:"")
print("b는 \(b)", terminator:"")
print("a+b 는 \(a+b)", terminator:"")

 

개행이 되지 않고 출력된다.

 

 

그 이외에도 다양한 사용법을이 존재하는데 처음 단계에서 이 모든 것을 알고 시작할 필요는 없다 생각한다. 그냥 print(str)만 기억하자.

 

 

728x90
반응형

댓글