Swift에서 명령 행 인수에 어떻게 액세스합니까?
Swift에서 명령 행 애플리케이션의 명령 행 인수에 어떻게 액세스합니까?
최상위 상수 C_ARGC
와를 사용하십시오 C_ARGV
.
for i in 1..C_ARGC {
let index = Int(i);
let arg = String.fromCString(C_ARGV[index])
switch arg {
case "this":
println("this yo");
case "that":
println("that yo")
default:
println("dunno bro")
}
}
"배열" 1..C_ARGC
의 첫 번째 요소 C_ARGV
가 응용 프로그램의 경로 이기 때문에 범위를 사용하고 있습니다 .
C_ARGV
변수 실제로 배열되지 않지만, 서브 스크립트 배열 같다.
01/17/17 업데이트 : Swift 3의 예가 업데이트 Process
되었습니다 CommandLine
.
2015 년 9 월 30 일 업데이트 : Swift 2에서 작동하도록 예제가 업데이트되었습니다.
Foundation 또는 C_ARGV
and 없이이 작업을 수행 할 수 있습니다 C_ARGC
.
Swift 표준 라이브러리에는 이라는 CommandLine
모음이있는 구조체 가 포함되어 있습니다 . 따라서 다음과 같은 인수를 켤 수 있습니다.String
arguments
for argument in CommandLine.arguments {
switch argument {
case "arg1":
print("first argument")
case "arg2":
print("second argument")
default:
print("an argument")
}
}
Swift 3에서는 CommandLine
대신 enum을 사용하십시오.Process
그래서:
let arguments = CommandLine.arguments
구식 "getopt"(Swift에서 사용 가능)를 사용하려는 사람은 이것을 참조로 사용할 수 있습니다. C에서 GNU 예제의 Swift 포트를 만들었습니다.
http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
전체 설명과 함께. 테스트되었으며 완벽하게 작동합니다. 재단도 필요하지 않습니다.
var aFlag = 0
var bFlag = 0
var cValue = String()
let pattern = "abc:"
var buffer = Array(pattern.utf8).map { Int8($0) }
while true {
let option = Int(getopt(C_ARGC, C_ARGV, buffer))
if option == -1 {
break
}
switch "\(UnicodeScalar(option))"
{
case "a":
aFlag = 1
println("Option -a")
case "b":
bFlag = 1
println("Option -b")
case "c":
cValue = String.fromCString(optarg)!
println("Option -c \(cValue)")
case "?":
let charOption = "\(UnicodeScalar(Int(optopt)))"
if charOption == "c" {
println("Option '\(charOption)' requires an argument.")
} else {
println("Unknown option '\(charOption)'.")
}
exit(1)
default:
abort()
}
}
println("aflag ='\(aFlag)', bflag = '\(bFlag)' cvalue = '\(cValue)'")
for index in optind..<C_ARGC {
println("Non-option argument '\(String.fromCString(C_ARGV[Int(index)])!)'")
}
참고 URL : https://stackoverflow.com/questions/24029633/how-do-you-access-command-line-arguments-in-swift
'Programming' 카테고리의 다른 글
자바 스크립트 가져 오기 구문에 대괄호 사용 (0) | 2020.08.05 |
---|---|
TypeScript 프로젝트에서 기존 C # 클래스 정의를 재사용하는 방법 (0) | 2020.08.05 |
SQLAlchemy 행 항목을 업데이트하는 방법? (0) | 2020.08.04 |
UITableView 일부 셀을 "선택 불가능"으로 설정 (0) | 2020.08.04 |
비밀번호를 해시하는 방법 (0) | 2020.08.04 |