repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nalexn/ViewInspector
|
Sources/ViewInspector/SwiftUI/GeometryReader.swift
|
1
|
2209
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct GeometryReader: KnownViewType {
public static var typePrefix: String = "GeometryReader"
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.GeometryReader: SingleViewContent {
public static func child(_ content: Content) throws -> Content {
let provider = try Inspector.cast(value: content.view, type: SingleViewProvider.self)
let medium = content.medium.resettingViewModifiers()
return try Inspector.unwrap(view: provider.view(), medium: medium)
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: SingleViewContent {
func geometryReader() throws -> InspectableView<ViewType.GeometryReader> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: MultipleViewContent {
func geometryReader(_ index: Int) throws -> InspectableView<ViewType.GeometryReader> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Private
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension GeometryReader: SingleViewProvider {
func view() throws -> Any {
typealias Builder = (GeometryProxy) -> Content
let builder = try Inspector
.attribute(label: "content", value: self, type: Builder.self)
return builder(GeometryProxy())
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension GeometryProxy {
struct Allocator48 {
let data: (Int64, Int64, Int64, Int64, Int64, Int64) = (0, 0, 0, 0, 0, 0)
}
struct Allocator52 {
let data: (Allocator48, Int32) = (.init(), 0)
}
init() {
if MemoryLayout<GeometryProxy>.size == 52 {
self = unsafeBitCast(Allocator52(), to: GeometryProxy.self)
return
}
self = unsafeBitCast(Allocator48(), to: GeometryProxy.self)
}
}
|
mit
|
1fb61907d41f73443f35e224e3c5aad2
| 30.112676 | 93 | 0.660027 | 3.937611 | false | false | false | false |
DanielAsher/Quick
|
Tests/QuickTests/QuickTests/FunctionalTests/PendingTests.swift
|
17
|
2343
|
import XCTest
import Quick
import Nimble
var oneExampleBeforeEachExecutedCount = 0
var onlyPendingExamplesBeforeEachExecutedCount = 0
class FunctionalTests_PendingSpec_Behavior: Behavior<Void> {
override static func spec(_ aContext: @escaping () -> Void) {
it("an example that will not run") {
expect(true).to(beFalsy())
}
}
}
class FunctionalTests_PendingSpec: QuickSpec {
override func spec() {
xit("an example that will not run") {
expect(true).to(beFalsy())
}
xitBehavesLike(FunctionalTests_PendingSpec_Behavior.self) { () -> Void in }
describe("a describe block containing only one enabled example") {
beforeEach { oneExampleBeforeEachExecutedCount += 1 }
it("an example that will run") {}
pending("an example that will not run") {}
}
describe("a describe block containing only pending examples") {
beforeEach { onlyPendingExamplesBeforeEachExecutedCount += 1 }
pending("an example that will not run") {}
}
}
}
final class PendingTests: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (PendingTests) -> () throws -> Void)] {
return [
("testAnOtherwiseFailingExampleWhenMarkedPendingDoesNotCauseTheSuiteToFail", testAnOtherwiseFailingExampleWhenMarkedPendingDoesNotCauseTheSuiteToFail),
("testBeforeEachOnlyRunForEnabledExamples", testBeforeEachOnlyRunForEnabledExamples),
("testBeforeEachDoesNotRunForContextsWithOnlyPendingExamples", testBeforeEachDoesNotRunForContextsWithOnlyPendingExamples)
]
}
func testAnOtherwiseFailingExampleWhenMarkedPendingDoesNotCauseTheSuiteToFail() {
let result = qck_runSpec(FunctionalTests_PendingSpec.self)
XCTAssertTrue(result!.hasSucceeded)
}
func testBeforeEachOnlyRunForEnabledExamples() {
oneExampleBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_PendingSpec.self)
XCTAssertEqual(oneExampleBeforeEachExecutedCount, 1)
}
func testBeforeEachDoesNotRunForContextsWithOnlyPendingExamples() {
onlyPendingExamplesBeforeEachExecutedCount = 0
qck_runSpec(FunctionalTests_PendingSpec.self)
XCTAssertEqual(onlyPendingExamplesBeforeEachExecutedCount, 0)
}
}
|
apache-2.0
|
f6098f4f691c37a054c3dd5648beea49
| 37.409836 | 163 | 0.708067 | 5.149451 | false | true | false | false |
StreamOneNL/iOS-SDK-ObjC
|
StreamOneSDK/MemorySessionStore.swift
|
1
|
8041
|
//
// MemorySessionStore.swift
// StreamOneSDK
//
// Created by Nicky Gerritsen on 07-08-15.
// Copyright © 2015 StreamOne. All rights reserved.
//
import Foundation
/**
In-memory session storage class
Values in instances of memory session store are only known for the lifetime of the instance, and
will be discarded once the instance is destroyed.
*/
public final class MemorySessionStore : NSObject, SessionStore {
/**
The current session ID; nil if no active session
*/
var id: String!
/**
The current session key; nil if no active session
*/
var key: String!
/**
The user ID of the user logged in with the current session; nil if no active session
*/
var userId: String!
/**
The current session timeout as absolute timestamp; nil if no active session
*/
var timeout: NSTimeInterval!
/**
Data store for cached values
*/
var cache = [String: AnyObject]()
/**
Whether there is an active session
*/
public var hasSession: Bool {
// All variables need to be set to a non-nil value for an active session
guard id != nil && key != nil && userId != nil && timeout != nil else { return false }
// The timeout must not have passed yed
if timeout < NSDate().timeIntervalSince1970 {
clearSession()
return false
}
// All checks passed; there is an active session
return true
}
/**
Clears the current active session
*/
public func clearSession() {
id = nil
key = nil
userId = nil
timeout = nil
cache = [String: AnyObject]()
}
/**
Save a session to this store
- Parameter id: The ID for this session
- Parameter key: The key for this session
- Parameter userId: The user ID for this session
- Parameter timeout: The number of seconds before this session becomes
invalid when not doing any requests
*/
public func setSession(id id: String, key: String, userId: String, timeout: NSTimeInterval) {
self.id = id
self.key = key
self.userId = userId
self.timeout = NSDate().timeIntervalSince1970 + timeout
}
/**
Update the timeout of a session
- Parameter timeout: The new timeout for the active session, in seconds from now
- Parameter error: if an error occurred, the error that occurred
*/
public func setTimeout(timeout: NSTimeInterval, error: NSErrorPointer) {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return
}
self.timeout = NSDate().timeIntervalSince1970 + timeout
}
/**
Retrieve the current session ID
This function will throw if there is no active session,
- Parameter error: if an error occurred, the error that occurred
- Returns: The current session ID
*/
public func getId(error: NSErrorPointer) -> String {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return ""
}
return id
}
/**
Retrieve the current session key
This function will throw if there is no active session.
- Parameter error: if an error occurred, the error that occurred
- Returns: The current session key
*/
public func getKey(error: NSErrorPointer) -> String {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return ""
}
return key
}
/**
Retrieve the ID of the user logged in with the current session
This function will throw if there is no active session.
- Parameter error: if an error occurred, the error that occurred
- Returns: The ID of the user logged in with the current session
*/
public func getUserId(error: NSErrorPointer) -> String {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return ""
}
return userId
}
/**
Retrieve the current session timeout
This function will throw if there is no active session.
- Parameter error: if an error occurred, the error that occurred
- Returns: The number of seconds before this session expires; negative if the session has expired
*/
public func getTimeout(error: NSErrorPointer) -> NSTimeInterval {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return -1
}
return timeout - NSDate().timeIntervalSince1970
}
/**
Check if a certain key is stored in the cache
- Parameter key: Cache key to check for existence
- Parameter error: if an error occurred, the error that occurred
- Returns: True if and only if the given key is set in the cache
*/
public func hasCacheKey(key: String, error: NSErrorPointer) -> Bool {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return false
}
return cache[key] != nil
}
/**
Retrieve a stored cache key
This function will throw if there is no active session or if hasCacheKey returns false
for the given key.
- Parameter key: Cache key to get the cached value of
- Parameter error: if an error occurred, the error that occurred
- Returns: The cached value
*/
public func getCacheKey(key: String, error: NSErrorPointer) -> AnyObject? {
var localError: NSError?
if !hasCacheKey(key, error: &localError) {
if let localError = localError {
error.memory = localError
} else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSuchKey.rawValue, userInfo: ["key": key])
}
return nil
}
return cache[key]!
}
/**
Store a cache key
This function will throw if there is no active session.
- Parameter key: Cache key to store a value for
- Parameter value: Value to store for the given key
- Parameter error: if an error occurred, the error that occurred
*/
public func setCacheKey(key: String, value: AnyObject, error: NSErrorPointer) {
guard hasSession else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSession.rawValue, userInfo: nil)
return
}
cache[key] = value
}
/**
Unset a cached value
This function will throw if there is no active session or if hasCacheKey returns false
for the given key.
- Parameter key: Cache key to unset
- Parameter error: if an error occurred, the error that occurred
*/
public func unsetCacheKey(key: String, error: NSErrorPointer) {
var localError: NSError?
if !hasCacheKey(key, error: &localError) {
if let localError = localError {
error.memory = localError
} else {
error.memory = NSError(domain: Constants.ErrorDomain, code: SessionError.NoSuchKey.rawValue, userInfo: ["key": key])
}
return
}
cache.removeValueForKey(key)
}
}
|
mit
|
5b76b3bba66053b9005fcf087c4f41f5
| 31.554656 | 132 | 0.602736 | 5.069357 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/Pods/SMCoreLib/SMCoreLib/Classes/Debugging/Log.swift
|
3
|
6552
|
//
// Log.swift
// WhatDidILike
//
// Created by Christopher Prince on 10/5/14.
// Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
// See http://stackoverflow.com/questions/24114288/macros-in-swift
// And http://stackoverflow.com/questions/24048430/logging-method-signature-using-swift/31737561#31737561
public class Log {
// In the default arguments to these functions:
// 1) If I use a String type, the macros (e.g., __LINE__) don't expand at run time.
// "\(__FUNCTION__)\(__FILE__)\(__LINE__)"
// 2) A tuple type, like,
// typealias SMLogFuncDetails = (String, String, Int)
// SMLogFuncDetails = (__FUNCTION__, __FILE__, __LINE__)
// doesn't work either.
// 3) This String = __FUNCTION__ + __FILE__
// also doesn't work.
public class func redirectConsoleLogToDocumentFolder(clearRedirectLog clearRedirectLog:Bool) {
LogFile.redirectConsoleLogToDocumentFolder(clearRedirectLog)
}
// That above redirect redirects the stderr, which is not what Swift uses by default:
// http://ericasadun.com/2015/05/22/swift-logging/
// http://stackoverflow.com/questions/24041554/how-can-i-output-to-stderr-with-swift
private class func logIt(string:String) {
if UIDevice.beingDebugged() {
// When attached to the debugger, print goes to the console.
print(string)
} else {
// When not attached to the debugger, this assumes we've redirected stderr to a file.
fputs(string, stderr)
}
}
public class func msg(message: String,
functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) {
#if DEBUG
let output = self.formatLogString(message, loggingColor: .Blue, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
logIt(output)
#endif
}
// For use in debugging only. Doesn't log to file. Marks output in red.
public class func error(message: String,
functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) {
#if DEBUG
let output = self.formatLogString(message, loggingColor: .Red, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
logIt(output)
#endif
}
// For use in debugging only. Doesn't log to file. Marks output in pink. (Yellow on white background is unreadable)
public class func warning(message: String,
functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) {
#if DEBUG
let output = self.formatLogString(message, loggingColor: .Pink, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
logIt(output)
#endif
}
// For use in debugging only. Doesn't log to file. Marks output in purple.
public class func special(message: String,
functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) {
#if DEBUG
let output = self.formatLogString(message, loggingColor: .Purple, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
logIt(output)
#endif
}
private enum SMLoggingColor {
case Red
case Yellow // Can't read this on a white background
case Blue
case Purple
case Pink
case None
}
private class func formatLogString(message: String, loggingColor:SMLoggingColor,
functionName: String, fileNameWithPath: String, lineNumber: Int) -> String {
let fileNameWithoutPath = (fileNameWithPath as NSString).lastPathComponent
var possiblyColoredMessage:String
switch (loggingColor) {
case .Red:
possiblyColoredMessage = SMColorLog.red(message)
case .Blue:
possiblyColoredMessage = SMColorLog.blue(message)
case .Yellow:
possiblyColoredMessage = SMColorLog.yellow(message)
case .Purple:
possiblyColoredMessage = SMColorLog.purple(message)
case .Pink:
possiblyColoredMessage = SMColorLog.pink(message)
case .None:
possiblyColoredMessage = message
}
let output = "\(NSDate()): \(possiblyColoredMessage) [\(functionName) in \(fileNameWithoutPath), line \(lineNumber)]"
return output
}
// Call this log method when something bad or important has happened.
public class func file(message: String,
functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) {
var output:String
#if DEBUG
// Log this in red because we typically log to a file because something important or bad has happened.
output = self.formatLogString(message, loggingColor: .Red, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
logIt(output)
#endif
output = self.formatLogString(message, loggingColor: .None, functionName: functionName, fileNameWithPath: fileNameWithPath, lineNumber: lineNumber)
LogFile.write(output + "\n")
}
}
// From https://github.com/robbiehanson/XcodeColors
// Use this with XcodeColors plugin.
struct SMColorLog {
static let ESCAPE = "\u{001b}["
static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color
static let RESET_BG = ESCAPE + "bg;" // Clear any background color
static let RESET = ESCAPE + ";" // Clear any foreground or background color
static func red<T>(object:T) -> String {
return "\(ESCAPE)fg255,0,0;\(object)\(RESET)"
}
static func green<T>(object:T) -> String {
return("\(ESCAPE)fg0,255,0;\(object)\(RESET)")
}
static func blue<T>(object:T) -> String {
return "\(ESCAPE)fg0,0,255;\(object)\(RESET)"
}
static func yellow<T>(object:T) -> String {
return "\(ESCAPE)fg255,255,0;\(object)\(RESET)"
}
static func purple<T>(object:T) -> String {
return "\(ESCAPE)fg255,0,255;\(object)\(RESET)"
}
static func pink<T>(object:T) -> String {
return "\(ESCAPE)fg255,105,180;\(object)\(RESET)"
}
static func cyan<T>(object:T) -> String {
return "\(ESCAPE)fg0,255,255;\(object)\(RESET)"
}
}
|
gpl-3.0
|
0266c990c533bb39eef9d8f0cc9a5da7
| 36.878613 | 161 | 0.639957 | 4.313364 | false | false | false | false |
liamnickell/inflation-calc
|
inflation-calc/MainViewController.swift
|
1
|
4976
|
//
// MainViewController.swift
// inflation-calc
//
// Created by Liam Nickell on 7/8/16.
// Copyright © 2016 Liam Nickell. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var appTitle: UILabel!
@IBOutlet weak var infCalcBtn: UIButton!
@IBOutlet weak var infCalcBtnEuro: UIButton!
@IBOutlet weak var infCalcBtnGpb: UIButton!
@IBOutlet weak var infCalcBtnJpy: UIButton!
@IBOutlet weak var infCalcBtnCad: UIButton!
@IBOutlet weak var infCalcBtnMxn: UIButton!
@IBOutlet weak var infForecastCalcBtn: UIButton!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
infCalcBtn.layer.cornerRadius = 6
infForecastCalcBtn.layer.cornerRadius = 6
infCalcBtnEuro.layer.cornerRadius = 6
infCalcBtnGpb.layer.cornerRadius = 6
infCalcBtnJpy.layer.cornerRadius = 6
infCalcBtnCad.layer.cornerRadius = 6
infCalcBtnMxn.layer.cornerRadius = 6
appTitle.adjustsFontSizeToFitWidth = true
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
if defaults.object(forKey: "darkKeyboard") == nil || defaults.object(forKey: "translucentKeyboardToolbar") == nil || defaults.object(forKey: "doneBtn") == nil || defaults.object(forKey: "doneBtnForecasts") == nil {
defaults.set(false, forKey: "darkKeyboard")
defaults.set(true, forKey: "translucentKeyboardToolbar")
defaults.set(false, forKey: "doneBtn")
defaults.set(false, forKey: "doneBtnForecasts")
}
}
override func viewWillDisappear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let btn: UIButton = sender as! UIButton
let tag = btn.tag
if tag != 6 && tag != 7 && tag != 8 {
let destinationVC: InfCalcViewController = segue.destination as! InfCalcViewController
if tag == 0 {
destinationVC.title = "USD Inflation"
destinationVC.path = Bundle.main.path(forResource: "CPI-Data", ofType: "txt")
destinationVC.maxYear = 1774
destinationVC.currencySymbol = "$"
destinationVC.reverseFileOrder = false
} else if tag == 1 {
destinationVC.title = "EUR Inflation"
destinationVC.path = Bundle.main.path(forResource: "EU-CPI-Data", ofType: "txt")
destinationVC.maxYear = 1996
destinationVC.currencySymbol = "€"
destinationVC.reverseFileOrder = true
} else if tag == 2 {
destinationVC.title = "GBP Inflation"
destinationVC.path = Bundle.main.path(forResource: "UK-CPI-Data", ofType: "txt")
destinationVC.maxYear = 1948
destinationVC.currencySymbol = "£"
destinationVC.reverseFileOrder = true
} else if tag == 3 {
destinationVC.title = "CAD Inflation"
destinationVC.path = Bundle.main.path(forResource: "CAD-CPI-Data", ofType: "txt")
destinationVC.maxYear = 1948
destinationVC.currencySymbol = "$"
destinationVC.reverseFileOrder = true
} else if tag == 4 {
destinationVC.title = "JPY Inflation"
destinationVC.path = Bundle.main.path(forResource: "Japan-CPI-Data", ofType: "txt")
destinationVC.maxYear = 1948
destinationVC.currencySymbol = "¥"
destinationVC.reverseFileOrder = true
destinationVC.isYen = true
} else if tag == 5 {
destinationVC.title = "MXN Inflation"
destinationVC.path = Bundle.main.path(forResource: "MEX-CPI-Data", ofType: "txt")
destinationVC.maxYear = 1948
destinationVC.currencySymbol = "$"
destinationVC.reverseFileOrder = true
}
destinationVC.keyboardIsDark = defaults.object(forKey: "darkKeyboard") as! Bool
destinationVC.keyboardToolbarIsTranslucent = defaults.object(forKey: "translucentKeyboardToolbar") as! Bool
destinationVC.doneBtnCalculates = defaults.object(forKey: "doneBtn") as! Bool
} else if tag == 6 {
let destinationVC = segue.destination as! ForecastingViewController
destinationVC.keyboardIsDark = defaults.object(forKey: "darkKeyboard") as! Bool
destinationVC.keyboardToolbarIsTranslucent = defaults.object(forKey: "translucentKeyboardToolbar") as! Bool
destinationVC.doneBtnForecasts = defaults.object(forKey: "doneBtnForecasts") as! Bool
}
}
}
|
mit
|
641f4043077578d3b625c119a76b6759
| 43.792793 | 222 | 0.61718 | 4.873529 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/UIImage+SwiftTweaks.swift
|
1
|
1483
|
//
// UIImage+SwiftTweaks.swift
// SwiftTweaks
//
// Created by Bryan Clark on 4/6/16.
// Copyright © 2016 Khan Academy. All rights reserved.
//
import UIKit
internal extension UIImage {
enum SwiftTweaksImage: String {
case disclosureIndicator = "disclosure-indicator"
case floatingPlusButton = "floating-plus-button"
case floatingCloseButton = "floating-ui-close"
case floatingMinimizedArrow = "floating-ui-minimized-arrow"
}
convenience init(swiftTweaksImage: SwiftTweaksImage) {
self.init(inThisBundleNamed: swiftTweaksImage.rawValue)!
}
// NOTE (bryan): if we just used UIImage(named:_), we get crashes when running in other apps!
// (Why? Because by default, iOS searches in your app's bundle, but we need to redirect that to the bundle associated with SwiftTweaks
private convenience init?(inThisBundleNamed imageName: String) {
self.init(named: imageName, in: Bundle(for: TweakTableCell.self), compatibleWith: nil) // NOTE (bryan): Could've used any class in SwiftTweaks here.
}
/// Returns the image, tinted to the given color.
internal func imageTintedWithColor(_ color: UIColor) -> UIImage {
let imageRect = CGRect(origin: CGPoint.zero, size: self.size)
UIGraphicsBeginImageContextWithOptions(imageRect.size, false, 0.0) // Retina aware.
draw(in: imageRect)
color.set()
UIRectFillUsingBlendMode(imageRect, .sourceIn)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
|
gpl-3.0
|
b26203a672277944f1f1d40d640d1000
| 31.933333 | 150 | 0.754386 | 3.849351 | false | false | false | false |
IngmarStein/swift
|
test/IDE/complete_members_optional.swift
|
1
|
1954
|
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift
// RUN: %target-swift-frontend -parse -verify -disable-objc-attr-requires-foundation-module %t_no_errors.swift
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_1 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_2 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_2
@objc
protocol HasOptionalMembers1 {
@objc optional func optionalInstanceFunc() -> Int
@objc optional static func optionalClassFunc() -> Int
@objc optional var optionalInstanceProperty: Int { get }
@objc optional static var optionalClassProperty: Int { get }
}
func sanityCheck1(_ a: HasOptionalMembers1) {
func isOptionalInt(_ a: inout Int?) {}
var result1 = a.optionalInstanceFunc?()
isOptionalInt(&result1)
var result2 = a.optionalInstanceProperty
isOptionalInt(&result2)
}
// NO_ERRORS_UP_TO_HERE
func optionalMembers1(_ a: HasOptionalMembers1) {
a.#^OPTIONAL_MEMBERS_1^#
}
// OPTIONAL_MEMBERS_1: Begin completions, 2 items
// OPTIONAL_MEMBERS_1-DAG: Decl[InstanceMethod]/CurrNominal: optionalInstanceFunc!()[#Int#]{{; name=.+$}}
// OPTIONAL_MEMBERS_1-DAG: Decl[InstanceVar]/CurrNominal: optionalInstanceProperty[#Int?#]{{; name=.+$}}
// OPTIONAL_MEMBERS_1: End completions
func optionalMembers2<T : HasOptionalMembers1>(_ a: T) {
T.#^OPTIONAL_MEMBERS_2^#
}
// OPTIONAL_MEMBERS_2: Begin completions, 3 items
// OPTIONAL_MEMBERS_2-DAG: Decl[InstanceMethod]/Super: optionalInstanceFunc!({#self: HasOptionalMembers1.Protocol#})[#() -> Int#]{{; name=.+$}}
// OPTIONAL_MEMBERS_2-DAG: Decl[StaticMethod]/Super: optionalClassFunc!()[#Int#]{{; name=.+$}}
// OPTIONAL_MEMBERS_2-DAG: Decl[StaticVar]/Super: optionalClassProperty[#Int?#]{{; name=.+$}}
// OPTIONAL_MEMBERS_2: End completions
|
apache-2.0
|
f62f95c70596678772af87862d66c044
| 44.44186 | 158 | 0.712385 | 3.565693 | false | false | false | false |
motoom/ios-apps
|
Pour3/Pour/SettingsController.swift
|
1
|
768
|
import UIKit
class SettingsController: UIViewController {
var vesselCount = 3
var difficulty = 5
@IBOutlet weak var vesselSlider: UISlider!
@IBOutlet weak var difficultySlider: UISlider!
@IBAction func adjustVessels(_ sender: UISlider) {
let roundedValue = round(sender.value)
sender.value = roundedValue
vesselCount = Int(sender.value)
}
@IBAction func adjustDifficulty(_ sender: UISlider) {
let roundedValue = round(sender.value)
sender.value = roundedValue
difficulty = Int(sender.value)
}
override func viewDidLoad() {
super.viewDidLoad()
vesselSlider.value = Float(vesselCount)
difficultySlider.value = Float(difficulty)
}
}
|
mit
|
d185e85f60004a004e5a5f7f9a09ac3a
| 23 | 57 | 0.64974 | 4.8 | false | false | false | false |
shabirjan/FyberOfferTask
|
OfferFramework/OfferFramework/OffersViewController.swift
|
1
|
3917
|
//
// OffersViewController.swift
// FyberOffer
//
// Created by Shabir Jan on 30/01/2017.
// Copyright © 2017 Shabir Jan. All rights reserved.
//
import UIKit
class OffersViewController: UIViewController {
weak var delegate: FyberOfferDelegate!
var options : FYBOfferOptions?
var networkManager : NetworkManager?
var parentController : UIViewController?
var allOffers = [FyberOfferModel]()
@IBOutlet weak var offerTableView: UITableView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var lblNoOffers: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
networkManager = NetworkManager(options: self.options!)
fetchOffers()
}
//Method to initiated NetworkManager class to fetch the offers and than display into the TableView
func fetchOffers(){
self.lblNoOffers.isHidden = true
allOffers = []
if self.options != nil {
activityIndicator.startAnimating()
networkManager?.fetchOffers(completion: { [weak self] offers in
self?.activityIndicator.stopAnimating()
if offers.count > 0 {
self?.allOffers = offers
self?.delegate?.offersRecevied!(totalOffers: offers.count)
self?.offerTableView.isHidden = false
self?.offerTableView.reloadData()
self?.delegate?.offersDidLoad!()
}
else{
self?.delegate?.offersLoadFailedWithError!(error: "No Offers found")
self?.lblNoOffers.isHidden = false
}
}
, failure: { (error) in
self.offerTableView.isHidden = true
self.lblNoOffers.isHidden = false
self.delegate?.offersLoadFailedWithError!(error: error)
self.activityIndicator.stopAnimating()
})
}
else{
self.delegate?.offersLoadFailedWithError!(error: "Invalid Options")
}
}
//Close the Controller
@IBAction func btnClosePressed(_ sender: Any) {
delegate?.offersDidClose!()
parentController?.dismiss(animated: true, completion: nil)
}
//Refresh the Offers
@IBAction func refreshOffers(_ sender: Any) {
fetchOffers()
}
}
//UITableView Delegate and DataSource methods
extension OffersViewController : UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 81
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allOffers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:OfferTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "offerCell") as? OfferTableViewCell
if cell == nil {
cell = OfferTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "offerCell")
}
let currentOffer = allOffers[indexPath.row]
cell?.lblTitle.text = currentOffer.offerTitle
networkManager?.fetchImage(url: currentOffer.offerThumbnail, completion: { (image) in
cell?.thumbnailImage.image = image
})
self.delegate?.offerDidLoadOnView!(offer: currentOffer)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedOffer = self.allOffers[indexPath.row]
self.delegate?.userSelectedOffer!(offer: selectedOffer)
}
}
|
mit
|
c53f1e2d83ab2a34ebe64fef0149beb3
| 32.758621 | 120 | 0.616445 | 5.371742 | false | false | false | false |
MrSuperJJ/JJSwiftNews
|
JJSwiftNews/View/JJNewsContentView.swift
|
1
|
5479
|
//
// JJNewsContentView.swift
// JJSwiftDemo
//
// Created by yejiajun on 2017/5/27.
// Copyright © 2017年 yejiajun. All rights reserved.
//
import UIKit
import SwiftyJSON
import SnapKit
class JJNewsContentView: UIView {
// MARK: - Properties
/// 资讯图片视图
private lazy var newsImageView: UIImageView = {
let newsImageView = UIImageView()
newsImageView.backgroundColor = UIColor.gray
return newsImageView
}()
/// 资讯文本内容视图
private lazy var newsContentView: UIView = {
let newsContentView = UIView()
newsContentView.backgroundColor = UIColor.clear
return newsContentView
}()
/// 资讯标题视图
private lazy var newsTitleLabel: UILabel = {
let newsTitleLabel = UILabel()
newsTitleLabel.font = UIFont.systemFont(ofSize: CGFloat(adValue: 14))
newsTitleLabel.numberOfLines = 0
return newsTitleLabel
}()
/// 资讯副标题视图
private lazy var newsSubTitleLabel: UILabel = {
let newsSubTitleLabel = UILabel()
newsSubTitleLabel.textColor = UIColor(valueRGB: 0x999999, alpha: 1)
newsSubTitleLabel.font = UIFont.systemFont(ofSize: CGFloat(adValue: 12))
return newsSubTitleLabel
}()
/// 分割线
private lazy var bottomLine: UIView = {
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor(valueRGB: 0xdcdcdc, alpha: 1)
return bottomLine
}()
// MARK: - Life Cycle
internal init(frame: CGRect, isPure: Bool) {
super.init(frame: frame)
self.setupViewFrame(isPure: isPure)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
// MARK: - 设置页面布局
internal func setupViewFrame(isPure: Bool) {
let subViewTop: CGFloat = 8
let subViewHeight: CGFloat = 60
self.addSubview(newsContentView)
newsContentView.addSubview(newsTitleLabel)
newsContentView.addSubview(newsSubTitleLabel)
self.addSubview(bottomLine)
// 资讯图片和内容
if isPure { // 纯文本界面
newsContentView.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(CGFloat(adValue:10))
make.top.equalTo(self).offset(CGFloat(adValue: subViewTop))
make.right.equalTo(self).offset(CGFloat(adValue:-10))
make.height.equalTo(CGFloat(adValue:subViewHeight))
}
} else { // 图文界面
self.addSubview(newsImageView)
newsImageView.snp.makeConstraints({ (make) in
make.left.equalTo(self).offset(CGFloat(adValue: 10))
make.top.equalTo(self).offset(CGFloat(adValue: subViewTop))
make.width.equalTo(CGFloat(adValue: 76.5))
make.height.equalTo(CGFloat(adValue: subViewHeight))
})
newsContentView.snp.makeConstraints { (make) in
make.left.equalTo(newsImageView.snp.right).offset(CGFloat(adValue:8))
make.top.equalTo(newsImageView)
make.right.equalTo(self).offset(CGFloat(adValue:-10))
make.height.equalTo(CGFloat(adValue:subViewHeight))
}
}
// 资讯标题
newsTitleLabel.snp.makeConstraints { (make) in
make.left.equalTo(newsContentView)
make.top.equalTo(newsContentView)
make.bottom.equalTo(newsSubTitleLabel.snp.top).offset(CGFloat(adValue: -6))
make.width.equalTo(newsContentView)
}
// 资讯副标题
newsSubTitleLabel.snp.makeConstraints { (make) in
make.left.equalTo(newsContentView)
make.bottom.equalTo(newsContentView)
make.width.equalTo(newsContentView)
make.height.equalTo(CGFloat(adValue: 12))
}
// 分割线
bottomLine.snp.makeConstraints { (make) in
make.bottom.equalTo(self).offset(-0.5)
make.width.equalTo(self)
make.height.equalTo(0.5)
}
}
// MARK: - 更新页面数据
internal func updateView(newsModel: JJNewsModelType) {
guard let newsModel = newsModel as? JJNewsModel else { return }
// 资讯图片
if !newsModel.isPure {
newsImageView.sd_setImage(with: URL(string: newsModel.imageLink))
}
// 资讯标题
let (_, attributedText) = heightAndTextForMultipleLinesText(newsModel.title, width: newsContentView.width, font: newsTitleLabel.font, lineSpacing: 5)
newsTitleLabel.attributedText = attributedText
// 资讯标题已读状态颜色
var titleTextColor = UIColor(valueRGB: 0x333333, alpha: 1)
let readedNewsDict = UserDefaults.standard.dictionary(forKey: kReadedNewsKey) as? [String : Bool]
if let readedNewsDict = readedNewsDict {
let uniqueKey = newsModel.uniquekey
let isNewsReaded = readedNewsDict["\(uniqueKey)"]
if let isNewsReaded = isNewsReaded, isNewsReaded == true {
titleTextColor = UIColor(valueRGB: 0x999999, alpha: 1)
}
}
newsTitleLabel.textColor = titleTextColor
// 资讯副标题
newsSubTitleLabel.text = newsModel.authorName
}
}
|
mit
|
7977c301be2c20fa7954f847412936fb
| 35.736111 | 157 | 0.623251 | 4.297319 | false | false | false | false |
kstaring/swift
|
stdlib/public/core/ShadowProtocols.swift
|
4
|
5964
|
//===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To implement bridging, the core standard library needs to interact
// a little bit with Cocoa. Because we want to keep the core
// decoupled from the Foundation module, we can't use foundation
// classes such as NSArray directly. We _can_, however, use an @objc
// protocols whose API is "layout-compatible" with that of NSArray,
// and use unsafe casts to treat NSArray instances as instances of
// that protocol.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@objc
public protocol _ShadowProtocol {}
/// A shadow for the `NSFastEnumeration` protocol.
@objc
public protocol _NSFastEnumeration : _ShadowProtocol {
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the `NSEnumerator` class.
@objc
public protocol _NSEnumerator : _ShadowProtocol {
init()
func nextObject() -> AnyObject?
}
/// A token that can be used for `NSZone*`.
public typealias _SwiftNSZone = OpaquePointer
/// A shadow for the `NSCopying` protocol.
@objc
public protocol _NSCopying : _ShadowProtocol {
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone?) -> AnyObject
}
/// A shadow for the "core operations" of NSArray.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSArray` subclass.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSArrayCore :
_NSCopying, _NSFastEnumeration {
@objc(objectAtIndex:)
func objectAt(_ index: Int) -> AnyObject
func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange)
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
var count: Int { get }
}
/// A shadow for the "core operations" of NSDictionary.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSDictionary` subclass.
@objc
public protocol _NSDictionaryCore :
_NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSDictionary subclass.
// The designated initializer of `NSDictionary`.
init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer, count: Int)
var count: Int { get }
@objc(objectForKey:)
func objectFor(_ aKey: AnyObject) -> AnyObject?
func keyEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone?) -> AnyObject
func getObjects(_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?)
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the API of `NSDictionary` we will use in the core
/// stdlib.
///
/// `NSDictionary` operations, in addition to those on
/// `_NSDictionaryCore`, that we need to use from the core stdlib.
/// Distinct from `_NSDictionaryCore` because we don't want to be
/// forced to implement operations that `NSDictionary` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSDictionary : _NSDictionaryCore {
// Note! This API's type is different from what is imported by the clang
// importer.
func getObjects(_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?)
}
/// A shadow for the "core operations" of NSSet.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSSet` subclass.
@objc
public protocol _NSSetCore :
_NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSSet subclass.
// The designated initializer of `NSSet`.
init(objects: UnsafePointer<AnyObject?>, count: Int)
var count: Int { get }
func member(_ object: AnyObject) -> AnyObject?
func objectEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone?) -> AnyObject
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int
}
/// A shadow for the API of NSSet we will use in the core
/// stdlib.
///
/// `NSSet` operations, in addition to those on
/// `_NSSetCore`, that we need to use from the core stdlib.
/// Distinct from `_NSSetCore` because we don't want to be
/// forced to implement operations that `NSSet` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSSet : _NSSetCore {
}
/// A shadow for the API of NSNumber we will use in the core
/// stdlib.
@objc
public protocol _NSNumber {
var doubleValue: Double { get }
var floatValue: Float { get }
var unsignedLongLongValue: UInt64 { get }
var longLongValue: Int64 { get }
var objCType: UnsafePointer<Int8> { get }
}
#else
public protocol _NSArrayCore {}
public protocol _NSDictionaryCore {}
public protocol _NSSetCore {}
#endif
|
apache-2.0
|
dc499a683e8734b355afa867cb97223b
| 30.225131 | 80 | 0.70892 | 4.514762 | false | false | false | false |
mirkofetter/TUIOSwift
|
TUIOSwift/main.swift
|
1
|
1590
|
//
// main.swift
// TUIOSwift
//
// Created by Mirko Fetter on 23.02.17.
// Copyright © 2017 grugru. All rights reserved.
//
import Foundation
let client = TUIOClient(port: 3333);
let listener1 = MyListener()
client.addTuioListener(listener: listener1)
client.connect()
//client.addTuioListener(listener: myListener)
//let oscServer = F53OSCServer.init()
//oscServer.port=UInt16(3333)
//oscServer.delegate=TUIOClient(port: 3333);
//oscServer.startListening()
let oscClient = F53OSCClient.init()
oscClient.host = "127.0.0.1"
oscClient.port = 3332
let addressPattern = "/tuio/2Dcur"
for index in 1 ..< 1000 {
var pos:Float = Float(100)/Float(50+index)
let arguments = ["source", "[email protected]"];
let message0 = F53OSCMessage(addressPattern: addressPattern, arguments: arguments)
let arguments1 = ["alive", 1] as [Any]
let message1 = F53OSCMessage(addressPattern: addressPattern, arguments: arguments1)
let arguments2 = ["set", 1, pos, pos , 0.5,0.5, 0.5] as [Any]
let message2 = F53OSCMessage(addressPattern: addressPattern, arguments: arguments2)
let arguments3 = ["fseq", index] as [Any]
let message3 = F53OSCMessage(addressPattern: addressPattern, arguments: arguments3)
let elements: [Any] = [message0!.packetData(), message1!.packetData(),message2!.packetData(),message3!.packetData()]
let bundle = F53OSCBundle(timeTag: F53OSCTimeTag.immediate(), elements: elements)
oscClient.send(bundle)
print("Sent '\(bundle!)' to \(oscClient.host!):\(oscClient.port)")
}
|
mit
|
86ca7dc25c902a6996730468c548067e
| 22.716418 | 120 | 0.688483 | 3.262834 | false | false | false | false |
LaszloPinter/CircleColorPicker
|
CircleColorPicker/ColorPicker/Views/CircleColorPickerView/CircleColorPickerView+TouchHandling.swift
|
1
|
3542
|
//Copyright (c) 2017 Laszlo Pinter
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
//
import UIKit
extension CircleColorPickerView { //Touch handling
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else{
return
}
let coordinate = touch.location(in: self)
if abs(coordinate.distanceTo(self.origo) - rainbowRadius) < bubbleRadius + rainbowWidth {
isBubbleDragged = true
onShouldMoveBubble(dragCoordinate: coordinate)
}
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else{
return
}
let coordinate = touch.location(in: self)
if isBubbleDragged {
onShouldMoveBubble(dragCoordinate: coordinate)
}
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard touches.first != nil else{
return
}
isBubbleDragged = false
}
private func onShouldMoveBubble(dragCoordinate: CGPoint) {
let dragAngle = calculateDesiredAngleFor(dragCoordinate: dragCoordinate)
UIView.animate(withDuration: animationTimeInSeconds, animations: {
self.colorBubbleView.transform = CGAffineTransform(rotationAngle: dragAngle)
let currentRads:CGFloat = CGFloat(atan2f(Float(self.colorBubbleView.transform.b), Float(self.colorBubbleView.transform.a)))
self.hue = self.rainbowCircleView.getHue(at: currentRads)
self.delegate?.onColorChanged(newColor: self.color)
})
}
private func calculateDesiredAngleFor(dragCoordinate: CGPoint) -> CGFloat{
let deltaInDegrees:Float = 5
let sectorSizeInDegrees:Float = 60
var dragAngle = CGVector(point: dragCoordinate - origo).angle.radiansToDegrees()
if dragAngle < 0 {
dragAngle = dragAngle + 360
}
let mod = fmodf(Float(dragAngle), sectorSizeInDegrees)
print(mod)
let partition = Int(Float(dragAngle) / sectorSizeInDegrees)
if mod < deltaInDegrees {
dragAngle = CGFloat(partition) * CGFloat(sectorSizeInDegrees)
}else if mod > 60 - deltaInDegrees {
dragAngle = CGFloat(partition+1) * CGFloat(sectorSizeInDegrees)
}
dragAngle = dragAngle.degreesToRadians()
return dragAngle
}
}
|
mit
|
58e586926b6721235d8a15554535f951
| 40.186047 | 135 | 0.67843 | 4.672823 | false | false | false | false |
jwfriese/Fleet
|
Fleet/CoreExtensions/UIBarButtonItem+Fleet.swift
|
1
|
1814
|
import UIKit
extension Fleet {
enum BarButtonItemError: FleetErrorDefinition {
case controlUnavailable(message: String)
case noTarget(title: String)
case noAction(title: String)
var errorMessage: String {
switch self {
case .controlUnavailable(let message):
return "Cannot tap UIBarButtonItem: \(message)"
case .noTarget(let title):
return "Attempted to tap UIBarButtonItem (title='\(title)') with no associated target."
case .noAction(let title):
return "Attempted to tap UIBarButtonItem (title='\(title)') with no associated action."
}
}
var name: NSExceptionName { get { return NSExceptionName(rawValue: "Fleet.BarButtonItemError") } }
}
}
extension UIBarButtonItem {
/**
Mimic a user tap on the bar button, firing any associated events.
- throws:
A `FleetError` if the bar button is not enabled, if it does not have
a target, or if it does not have an action.
*/
public func tap() {
guard isEnabled else {
FleetError(Fleet.BarButtonItemError.controlUnavailable(message: "Control is not enabled.")).raise()
return
}
guard let target = target else {
FleetError(Fleet.BarButtonItemError.noTarget(title: safeTitle)).raise()
return
}
guard let action = action else {
FleetError(Fleet.BarButtonItemError.noAction(title: safeTitle)).raise()
return
}
let _ = target.perform(action, with: self)
}
fileprivate var safeTitle: String {
get {
if let title = title {
return title
}
return "<No Title>"
}
}
}
|
apache-2.0
|
1baa74dacd99b8a91137110a725d38e8
| 28.737705 | 111 | 0.5871 | 4.983516 | false | false | false | false |
JGiola/swift-package-manager
|
Sources/SPMLLBuild/llbuild.swift
|
1
|
4999
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
// We either export the llbuildSwift shared library or the llbuild framework.
#if canImport(llbuildSwift)
@_exported import llbuildSwift
@_exported import llbuild
#else
@_exported import llbuild
#endif
import Foundation
/// An llbuild value.
public protocol LLBuildValue: Codable {
}
/// An llbuild key.
public protocol LLBuildKey: Codable {
/// The value that this key computes.
associatedtype BuildValue: LLBuildValue
/// The rule that this key operates on.
associatedtype BuildRule: LLBuildRule
}
public protocol LLBuildEngineDelegate {
func lookupRule(rule: String, key: Key) -> Rule
}
public final class LLBuildEngine {
private final class Delegate: BuildEngineDelegate {
let delegate: LLBuildEngineDelegate
init(_ delegate: LLBuildEngineDelegate) {
self.delegate = delegate
}
func lookupRule(_ key: Key) -> Rule {
let ruleKey = RuleKey(key)
return delegate.lookupRule(
rule: ruleKey.rule, key: Key(ruleKey.data))
}
}
private let engine: BuildEngine
public init(delegate: LLBuildEngineDelegate) {
engine = BuildEngine(delegate: Delegate(delegate))
}
deinit {
engine.close()
}
public func build<T: LLBuildKey>(key: T) -> T.BuildValue {
let encodedKey = RuleKey(
rule: T.BuildRule.ruleName, data: key.toKey().data).toKey()
let value = engine.build(key: encodedKey)
return T.BuildValue(value)
}
public func attachDB(path: String, schemaVersion: Int = 0) throws {
try engine.attachDB(path: path, schemaVersion: schemaVersion)
}
public func close() {
engine.close()
}
}
// FIXME: Rename to something else.
public class LLTaskBuildEngine {
let engine: TaskBuildEngine
init(_ engine: TaskBuildEngine) {
self.engine = engine
}
public func taskNeedsInput<T: LLBuildKey>(_ key: T, inputID: Int) {
let encodedKey = RuleKey(
rule: T.BuildRule.ruleName, data: key.toKey().data).toKey()
engine.taskNeedsInput(encodedKey, inputID: inputID)
}
public func taskIsComplete<T: LLBuildValue>(_ result: T) {
engine.taskIsComplete(result.toValue(), forceChange: false)
}
}
/// An individual build rule.
open class LLBuildRule: Rule, Task {
/// The name of the rule.
///
/// This name will be available in the delegate's lookupRule(rule:key:).
open class var ruleName: String {
fatalError("subclass responsibility")
}
public init() {
}
public func createTask() -> Task {
return self
}
public func start(_ engine: TaskBuildEngine) {
self.start(LLTaskBuildEngine(engine))
}
public func provideValue(_ engine: TaskBuildEngine, inputID: Int, value: Value) {
self.provideValue(LLTaskBuildEngine(engine), inputID: inputID, value: value)
}
public func inputsAvailable(_ engine: TaskBuildEngine) {
self.inputsAvailable(LLTaskBuildEngine(engine))
}
// MARK:-
open func isResultValid(_ priorValue: Value) -> Bool {
return true
}
open func start(_ engine: LLTaskBuildEngine) {
}
open func provideValue(_ engine: LLTaskBuildEngine, inputID: Int, value: Value) {
}
open func inputsAvailable(_ engine: LLTaskBuildEngine) {
}
}
// MARK:- Helpers
private struct RuleKey: Codable {
let rule: String
let data: [UInt8]
init(rule: String, data: [UInt8]) {
self.rule = rule
self.data = data
}
init(_ key: Key) {
self.init(key.data)
}
init(_ data: [UInt8]) {
self = try! fromBytes(data)
}
func toKey() -> Key {
return try! Key(toBytes(self))
}
}
public extension LLBuildKey {
init(_ key: Key) {
self.init(key.data)
}
init(_ data: [UInt8]) {
self = try! fromBytes(data)
}
func toKey() -> Key {
return try! Key(toBytes(self))
}
}
public extension LLBuildValue {
init(_ value: Value) {
self = try! fromBytes(value.data)
}
func toValue() -> Value {
return try! Value(toBytes(self))
}
}
private func fromBytes<T: Decodable>(_ bytes: [UInt8]) throws -> T {
var bytes = bytes
let data = Data(bytes: &bytes, count: bytes.count)
return try JSONDecoder().decode(T.self, from: data)
}
private func toBytes<T: Encodable>(_ value: T) throws -> [UInt8] {
let encoder = JSONEncoder()
if #available(macOS 10.13, *) {
encoder.outputFormatting = [.sortedKeys]
}
let encoded = try encoder.encode(value)
return [UInt8](encoded)
}
|
apache-2.0
|
73e30bfb8984a3b94d526df7fa00acc9
| 23.149758 | 85 | 0.637528 | 3.930031 | false | false | false | false |
B-Lach/PocketCastsKit
|
SharedSource/API/NetworkManager/RestClient.swift
|
1
|
1910
|
//
// RestClient.swift
// PocketCastsKit
//
// Created by Benny Lach on 17.08.17.
// Copyright © 2017 Benny Lach. All rights reserved.
//
import Foundation
enum RestClientErrors: Error {
case baseURLStringNotValid(stirng: String)
case pathNotValid(path: String)
}
/// RestClient (atm only GET and POST) to make Network Requests
class RestClient: RestProtocol {
private let manager: NetworkManager
private(set) var baseURL: URL
/// Contructor
///
/// - Parameters:
/// - baseURLString: The Base URL of the Backend as String
/// - manager: (optional) The underlying Manager to make the Request - Can be set for Unit Testing
/// - Throws: If the given Base URL String is not valid
init(baseURLString: String, manager: NetworkManager = NetworkManager()) throws {
guard let url = URL(string: baseURLString) else {
throw RestClientErrors.baseURLStringNotValid(stirng: baseURLString)
}
self.baseURL = url
self.manager = manager
}
func get(path: String, options: [RequestOption] = [], completion: @escaping ((Result<(Data, HTTPURLResponse)>) -> Void)) {
guard let url = URL(string: path, relativeTo: baseURL)?.absoluteURL else {
completion(Result.error(RestClientErrors.pathNotValid(path: path)))
return
}
manager.makeRequest(url: url, options: options, method: .GET, completion: completion)
}
func post(path: String, options: [RequestOption] = [], completion: @escaping ((Result<(Data, HTTPURLResponse)>) -> Void)) {
guard let url = URL(string: path, relativeTo: baseURL)?.absoluteURL else {
completion(Result.error(RestClientErrors.pathNotValid(path: path)))
return
}
manager.makeRequest(url: url, options: options, method: .POST, completion: completion)
}
}
|
mit
|
952b06ed6063ae1db68ccd705c4ae34d
| 35.711538 | 127 | 0.648507 | 4.439535 | false | false | false | false |
segmentio/analytics-ios
|
SegmentTests/StoreKitTrackerTests.swift
|
1
|
1817
|
//
// StoreKitTrackerTest.swift
// Analytics
//
// Created by Tony Xiao on 9/20/16.
// Copyright © 2016 Segment. All rights reserved.
//
import Segment
import XCTest
class mockTransaction: SKPaymentTransaction {
override var transactionIdentifier: String? {
return "tid"
}
override var transactionState: SKPaymentTransactionState {
return SKPaymentTransactionState.purchased
}
override var payment: SKPayment {
return mockPayment()
}
}
class mockPayment: SKPayment {
override var productIdentifier: String { return "pid" }
}
class mockProduct: SKProduct {
override var productIdentifier: String { return "pid" }
override var price: NSDecimalNumber { return 3 }
override var localizedTitle: String { return "lt" }
}
class mockProductResponse: SKProductsResponse {
override var products: [SKProduct] {
return [mockProduct()]
}
}
class StoreKitTrackerTests: XCTestCase {
var test: TestMiddleware!
var tracker: StoreKitTracker!
var analytics: Analytics!
override func setUp() {
super.setUp()
let config = AnalyticsConfiguration(writeKey: "foobar")
test = TestMiddleware()
config.sourceMiddleware = [test]
analytics = Analytics(configuration: config)
tracker = StoreKitTracker.trackTransactions(for: analytics)
}
func testSKPaymentQueueObserver() {
let transaction = mockTransaction()
XCTAssertEqual(transaction.transactionIdentifier, "tid")
tracker.paymentQueue(SKPaymentQueue(), updatedTransactions: [transaction])
tracker.productsRequest(SKProductsRequest(), didReceive: mockProductResponse())
let payload = test.lastContext?.payload as? TrackPayload
XCTAssertEqual(payload?.event, "Order Completed")
}
}
|
mit
|
af1b15349158225227c1526429158f93
| 26.104478 | 87 | 0.700991 | 4.88172 | false | true | false | false |
HarwordLiu/Ing.
|
Ing/Ing/Operations/CKRecordOperations/FetchRecordChangesForCloudKitZoneOperation.swift
|
1
|
3127
|
//
// FetchRecordChangesForCloudKitZoneOperation.swift
// CloudKitSyncPOC
//
// Created by Nick Harris on 1/17/16.
// Copyright © 2016 Nick Harris. All rights reserved.
//
import CloudKit
import CoreData
class FetchRecordChangesForCloudKitZoneOperation: CKFetchRecordChangesOperation {
var changedRecords: [CKRecord]
var deletedRecordIDs: [CKRecordID]
var operationError: NSError?
fileprivate let cloudKitZone: CloudKitZone
init(cloudKitZone: CloudKitZone) {
self.cloudKitZone = cloudKitZone
self.changedRecords = []
self.deletedRecordIDs = []
super.init()
self.recordZoneID = cloudKitZone.recordZoneID()
self.previousServerChangeToken = getServerChangeToken(cloudKitZone)
}
override func main() {
print("FetchCKRecordChangesForCloudKitZoneOperation.main() - \(String(describing: previousServerChangeToken))")
setOperationBlocks()
super.main()
}
// MARK: Set operation blocks
func setOperationBlocks() {
recordChangedBlock = {
[unowned self]
(record: CKRecord) -> Void in
print("Record changed: \(record)")
self.changedRecords.append(record)
}
recordWithIDWasDeletedBlock = {
[unowned self]
(recordID: CKRecordID) -> Void in
print("Record deleted: \(recordID)")
self.deletedRecordIDs.append(recordID)
}
fetchRecordChangesCompletionBlock = {
[unowned self]
(serverChangeToken: CKServerChangeToken?, clientChangeToken: Data?, error: NSError?) -> Void in
if let operationError = error {
print("SyncRecordChangesToCoreDataOperation resulted in an error: \(String(describing: error))")
self.operationError = operationError
}
else {
self.setServerChangeToken(self.cloudKitZone, serverChangeToken: serverChangeToken)
}
} as? (CKServerChangeToken?, Data?, Error?) -> Void
}
// MARK: Change token user default methods
func getServerChangeToken(_ cloudKitZone: CloudKitZone) -> CKServerChangeToken? {
let encodedObjectData = UserDefaults.standard.object(forKey: cloudKitZone.serverTokenDefaultsKey()) as? Data
if let encodedObjectData = encodedObjectData {
return NSKeyedUnarchiver.unarchiveObject(with: encodedObjectData) as? CKServerChangeToken
}
else {
return nil
}
}
func setServerChangeToken(_ cloudKitZone: CloudKitZone, serverChangeToken: CKServerChangeToken?) {
if let serverChangeToken = serverChangeToken {
UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: serverChangeToken), forKey:cloudKitZone.serverTokenDefaultsKey())
}
else {
UserDefaults.standard.set(nil, forKey:cloudKitZone.serverTokenDefaultsKey())
}
}
}
|
mit
|
fe2697bb920fd70d04069918f0f52166
| 32.255319 | 148 | 0.627639 | 5.532743 | false | false | false | false |
siberianisaev/NeutronBarrel
|
NeutronBarrel/DataProtocol.swift
|
1
|
9353
|
//
// DataProtocol.swift
// NeutronBarrel
//
// Created by Andrey Isaev on 24/04/2017.
// Copyright © 2018 Flerov Laboratory. All rights reserved.
//
import Foundation
import AppKit
enum TOFKind: String {
case TOF = "TOF"
case TOF2 = "TOF2"
}
class DataProtocol {
fileprivate var dict = [String: Int]() {
didSet {
AVeto = dict["AVeto"]
TOF = dict[TOFKind.TOF.rawValue]
TOF2 = dict[TOFKind.TOF2.rawValue]
NeutronsOld = dict["Neutrons"]
Neutrons_N = getValues(ofTypes: ["N1", "N2", "N3", "N4"], prefix: false)
NeutronsNew = getValues(ofTypes: ["NNeut"])
CycleTime = dict["THi"]
BeamEnergy = dict["EnergyHi"]
BeamCurrent = dict["BeamTokHi"]
BeamBackground = dict["BeamFonHi"]
BeamIntegral = dict["IntegralHi"]
AlphaWell = getValues(ofTypes: ["AWel"])
AlphaWellFront = getValues(ofTypes: ["AWFr"])
AlphaWellBack = getValues(ofTypes: ["AWBk"])
AlphaMotherFront = getValues(ofTypes: ["AFr"])
AlphaDaughterFront = getValues(ofTypes: ["AdFr"])
AlphaFront = AlphaMotherFront.union(AlphaDaughterFront)
AlphaMotherBack = getValues(ofTypes: ["ABack", "ABk"])
AlphaDaughterBack = getValues(ofTypes: ["AdBk"])
AlphaBack = AlphaMotherBack.union(AlphaDaughterBack)
Gamma = getValues(ofTypes: ["Gam"])
}
}
fileprivate func getValues(ofTypes types: [String], prefix: Bool = true) -> Set<Int> {
var result = [Int]()
for type in types {
let values = dict.filter({ (key: String, value: Int) -> Bool in
if prefix {
return self.keyFor(value: value)?.hasPrefix(type) == true
} else {
return self.keyFor(value: value) == type
}
}).values
result.append(contentsOf: values)
}
return Set(result)
}
fileprivate var BeamEnergy: Int?
fileprivate var BeamCurrent: Int?
fileprivate var BeamBackground: Int?
fileprivate var BeamIntegral: Int?
fileprivate var AVeto: Int?
fileprivate var TOF: Int?
fileprivate var TOF2: Int?
fileprivate var NeutronsOld: Int?
fileprivate var Neutrons_N = Set<Int>()
fileprivate var NeutronsNew = Set<Int>()
fileprivate var CycleTime: Int?
fileprivate var AlphaWell = Set<Int>()
fileprivate var AlphaWellFront = Set<Int>()
fileprivate var AlphaWellBack = Set<Int>()
fileprivate var AlphaMotherFront = Set<Int>()
fileprivate var AlphaDaughterFront = Set<Int>()
fileprivate var AlphaFront = Set<Int>()
fileprivate var AlphaMotherBack = Set<Int>()
fileprivate var AlphaDaughterBack = Set<Int>()
fileprivate var AlphaBack = Set<Int>()
fileprivate var Gamma = Set<Int>()
fileprivate var isAlphaCache = [Int: Bool]()
func isAlpha(eventId: Int) -> Bool {
if let b = isAlphaCache[eventId] {
return b
} else {
var b = false
for s in [AlphaFront, AlphaBack, AlphaWell, AlphaWellFront, AlphaWellBack, AlphaMotherFront, AlphaMotherBack, AlphaDaughterFront, AlphaDaughterBack] {
if s.contains(eventId) {
b = true
break
}
}
isAlphaCache[eventId] = b
return b
}
}
class func load(_ path: String?) -> DataProtocol {
var result = [String: Int]()
if let path = path {
do {
var content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
content = content.replacingOccurrences(of: " ", with: "")
let words = Event.words
for line in content.components(separatedBy: CharacterSet.newlines) {
if false == line.contains(":") || line.starts(with: "#") {
continue
}
let set = CharacterSet(charactersIn: ":,")
let components = line.components(separatedBy: set).filter() { $0 != "" }
let count = components.count
if words == count {
let key = components[count-1]
let value = Int(components[0])
result[key] = value
}
}
} catch {
print("Error load protocol from file at path \(path): \(error)")
}
}
let p = DataProtocol()
p.dict = result
if p.dict.count == 0 {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Please select protocol!"
alert.addButton(withTitle: "OK")
alert.alertStyle = .warning
alert.runModal()
}
p.encoderForEventIdCache.removeAll()
p.isValidEventIdForTimeCheckCache.removeAll()
return p
}
fileprivate var isValidEventIdForTimeCheckCache = [Int: Bool]()
/**
Not all events have time data.
*/
func isValidEventIdForTimeCheck(_ eventId: Int) -> Bool {
if let cached = isValidEventIdForTimeCheckCache[eventId] {
return cached
}
let value = isAlpha(eventId: eventId) || isTOFEvent(eventId) != nil || isGammaEvent(eventId) || isNeutronsOldEvent(eventId) || isNeutronsNewEvent(eventId) || isNeutrons_N_Event(eventId) || isVETOEvent(eventId)
isValidEventIdForTimeCheckCache[eventId] = value
return value
}
func keyFor(value: Int) -> String? {
for (k, v) in dict {
if v == value {
return k
}
}
return nil
}
func position(_ eventId: Int) -> String {
if AlphaMotherFront.contains(eventId) {
return "Fron"
} else if AlphaMotherBack.contains(eventId) {
return "Back"
} else if AlphaDaughterFront.contains(eventId) {
return "dFron"
} else if AlphaDaughterBack.contains(eventId) {
return "dBack"
} else if isVETOEvent(eventId) {
return "Veto"
} else if isGammaEvent(eventId) {
return "Gam"
} else if isAlphaWellBackEvent(eventId) {
return "WBack"
} else if isAlphaWellFrontEvent(eventId) {
return "WFront"
} else {
return "Wel"
}
}
func isAlphaFronEvent(_ eventId: Int) -> Bool {
return AlphaFront.contains(eventId)
}
func isAlphaBackEvent(_ eventId: Int) -> Bool {
return AlphaBack.contains(eventId)
}
func isAlphaWellEvent(_ eventId: Int) -> Bool {
return AlphaWell.contains(eventId)
}
func isAlphaWellFrontEvent(_ eventId: Int) -> Bool {
return AlphaWellFront.contains(eventId)
}
func isAlphaWellBackEvent(_ eventId: Int) -> Bool {
return AlphaWellBack.contains(eventId)
}
func isGammaEvent(_ eventId: Int) -> Bool {
return Gamma.contains(eventId)
}
func isVETOEvent(_ eventId: Int) -> Bool {
return AVeto == eventId
}
func isTOFEvent(_ eventId: Int) -> TOFKind? {
if TOF == eventId {
return .TOF
} else if TOF2 == eventId {
return .TOF2
}
return nil
}
func isNeutronsNewEvent(_ eventId: Int) -> Bool {
return NeutronsNew.contains(eventId)
}
func isNeutronsOldEvent(_ eventId: Int) -> Bool {
return NeutronsOld == eventId
}
func isNeutrons_N_Event(_ eventId: Int) -> Bool {
return Neutrons_N.contains(eventId)
}
func hasNeutrons_N() -> Bool {
return Neutrons_N.count > 0
}
func isCycleTimeEvent(_ eventId: Int) -> Bool {
return CycleTime == eventId
}
func isBeamEnergy(_ eventId: Int) -> Bool {
return BeamEnergy == eventId
}
func isBeamCurrent(_ eventId: Int) -> Bool {
return BeamCurrent == eventId
}
func isBeamBackground(_ eventId: Int) -> Bool {
return BeamBackground == eventId
}
func isBeamIntegral(_ eventId: Int) -> Bool {
return BeamIntegral == eventId
}
fileprivate var encoderForEventIdCache = [Int: CUnsignedShort]()
func encoderForEventId(_ eventId: Int) -> CUnsignedShort {
if let cached = encoderForEventIdCache[eventId] {
return cached
}
var value: CUnsignedShort
if let key = keyFor(value: eventId), let rangeDigits = key.rangeOfCharacter(from: .decimalDigits), let substring = String(key[rangeDigits.lowerBound...]).components(separatedBy: CharacterSet.init(charactersIn: "., ")).first, let encoder = Int(substring) {
value = CUnsignedShort(encoder)
} else if (AlphaWell.contains(eventId) && AlphaWell.count == 1) || (Gamma.contains(eventId) && Gamma.count == 1) {
value = 1
} else {
value = 0
}
encoderForEventIdCache[eventId] = value
return value
}
}
|
mit
|
56ba36432b7d8ad83e6374f4a85f0aa2
| 32.4 | 263 | 0.557314 | 4.384435 | false | false | false | false |
sindresorhus/touch-bar-simulator
|
Touch Bar Simulator/App.swift
|
1
|
5925
|
import SwiftUI
import Sparkle
import Defaults
import LaunchAtLogin
import KeyboardShortcuts
final class AppDelegate: NSObject, NSApplicationDelegate {
private(set) lazy var window = with(TouchBarWindow()) {
$0.alphaValue = Defaults[.windowTransparency]
$0.setUp()
}
private(set) lazy var statusItem = with(NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)) {
$0.menu = with(NSMenu()) {
$0.delegate = self
}
$0.button!.image = NSImage(named: "MenuBarIcon")
$0.button!.toolTip = "Right-click or option-click for menu"
$0.button!.preventsHighlight = true
}
private lazy var updateController = SPUStandardUpdaterController(startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
func applicationWillFinishLaunching(_ notification: Notification) {
UserDefaults.standard.register(defaults: [
"NSApplicationCrashOnExceptions": true
])
}
func applicationDidFinishLaunching(_ notification: Notification) {
checkAccessibilityPermission()
_ = updateController
_ = window
_ = statusItem
KeyboardShortcuts.onKeyUp(for: .toggleTouchBar) { [self] in
toggleView()
}
}
func checkAccessibilityPermission() {
// We intentionally don't use the system prompt as our dialog explains it better.
let options = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as String: false] as CFDictionary
if AXIsProcessTrustedWithOptions(options) {
return
}
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility".openUrl()
let alert = NSAlert()
alert.messageText = "Touch Bar Simulator needs accessibility access."
alert.informativeText = "In the System Preferences window that just opened, find “Touch Bar Simulator” in the list and check its checkbox. Then click the “Continue” button here."
alert.addButton(withTitle: "Continue")
alert.addButton(withTitle: "Quit")
guard alert.runModal() == .alertFirstButtonReturn else {
SSApp.quit()
return
}
SSApp.relaunch()
}
@objc
func captureScreenshot() {
let KEY_6: CGKeyCode = 0x58
pressKey(keyCode: KEY_6, flags: [.maskShift, .maskCommand])
}
func toggleView() {
window.setIsVisible(!window.isVisible)
}
}
extension AppDelegate: NSMenuDelegate {
private func update(menu: NSMenu) {
menu.removeAllItems()
guard statusItemShouldShowMenu() else {
return
}
menu.addItem(NSMenuItem(title: "Docking", action: nil, keyEquivalent: ""))
var statusMenuDockingItems: [NSMenuItem] = []
statusMenuDockingItems.append(NSMenuItem("Floating").bindChecked(to: .windowDocking, value: .floating))
statusMenuDockingItems.append(NSMenuItem("Docked to Top").bindChecked(to: .windowDocking, value: .dockedToTop))
statusMenuDockingItems.append(NSMenuItem("Docked to Bottom").bindChecked(to: .windowDocking, value: .dockedToBottom))
for item in statusMenuDockingItems {
item.indentationLevel = 1
}
menu.items.append(contentsOf: statusMenuDockingItems)
func sliderMenuItem(_ title: String, boundTo key: Defaults.Key<Double>, min: Double, max: Double) -> NSMenuItem {
let menuItem = NSMenuItem(title)
let containerView = NSView(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 20)))
let slider = MenubarSlider().alwaysRedisplayOnValueChanged()
slider.frame = CGRect(x: 20, y: 4, width: 180, height: 11)
slider.minValue = min
slider.maxValue = max
slider.bindDoubleValue(to: key)
containerView.addSubview(slider)
slider.translatesAutoresizingMaskIntoConstraints = false
slider.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 24).isActive = true
slider.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -9).isActive = true
slider.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
menuItem.view = containerView
return menuItem
}
if Defaults[.windowDocking] != .floating {
menu.addItem(NSMenuItem("Padding"))
menu.addItem(sliderMenuItem("Padding", boundTo: .windowPadding, min: 0.0, max: 120.0))
}
menu.addItem(NSMenuItem("Opacity"))
menu.addItem(sliderMenuItem("Opacity", boundTo: .windowTransparency, min: 0.5, max: 1.0))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem("Capture Screenshot", keyEquivalent: "6", keyModifiers: [.shift, .command]) { [self] _ in
captureScreenshot()
})
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem("Show on All Desktops").bindState(to: .showOnAllDesktops))
menu.addItem(NSMenuItem("Hide and Show Automatically").bindState(to: .dockBehavior))
menu.addItem(NSMenuItem("Launch at Login", isChecked: LaunchAtLogin.isEnabled) { item in
item.isChecked.toggle()
LaunchAtLogin.isEnabled = item.isChecked
})
menu.addItem(NSMenuItem("Keyboard Shortcuts…") { [self] _ in
guard let button = statusItem.button else {
return
}
let popover = NSPopover()
popover.contentViewController = NSHostingController(rootView: KeyboardShortcutsView())
popover.behavior = .transient
popover.show(relativeTo: button.frame, of: button, preferredEdge: .maxY)
})
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem("Quit Touch Bar Simulator", keyEquivalent: "q") { _ in
NSApp.terminate(nil)
})
}
private func statusItemShouldShowMenu() -> Bool {
!NSApp.isLeftMouseDown || NSApp.isOptionKeyDown
}
func menuNeedsUpdate(_ menu: NSMenu) {
update(menu: menu)
}
func menuWillOpen(_ menu: NSMenu) {
let shouldShowMenu = statusItemShouldShowMenu()
statusItem.button!.preventsHighlight = !shouldShowMenu
if !shouldShowMenu {
statusItemButtonClicked()
}
}
private func statusItemButtonClicked() {
// When the user explicitly wants the Touch Bar to appear then `dockBahavior` should be disabled.
// This is also how the macOS Dock behaves.
Defaults[.dockBehavior] = false
toggleView()
if window.isVisible {
window.orderFront(nil)
}
}
}
|
mit
|
dbb6ed6d189897fd525ce0c6dfe89a39
| 31.322404 | 180 | 0.743533 | 3.781969 | false | false | false | false |
scottkawai/sendgrid-swift
|
Sources/SendGrid/Structs/Authentication.swift
|
1
|
2202
|
import Foundation
/// The `Authentication` struct is used to authenticate all the requests made by
/// `Session`.
public struct Authentication: CustomStringConvertible {
// MARK: - Properties
/// The prefix used in the authorization header.
public let prefix: String
/// The value of the authorization header.
public let value: String
/// A description for the type of the authorization.
public let description: String
/// Returns that `Authorization` header value for the authentication type.
/// This can be used on any web API V3 call.
public var authorizationHeader: String { "\(self.prefix) \(self.value)" }
// MARK: - Initialization
/// Initializes the struct.
///
/// - parameter prefix: The prefix used in the authorization header.
/// - parameter value: The value of the authorization header.
/// - parameter description: A description of the authentication type.
public init(prefix: String, value: String, description: String) {
self.prefix = prefix
self.value = value
self.description = description
}
}
public extension Authentication {
/// Creates an `Authentication` instance representing an API key.
///
/// - parameter key: The SendGrid API key to use.
///
/// - returns: An `Authentication` instance.
static func apiKey(_ key: String) -> Authentication {
Authentication(prefix: "Bearer", value: key, description: "API Key")
}
/// Creates an `Authentication` instance representing a username and
/// password.
///
/// - parameter username: The SendGrid username key to use.
/// - parameter password: The SendGrid password key to use.
///
/// - returns: An `Authentication` instance.
static func credential(username: String, password: String) throws -> Authentication {
let str = "\(username):\(password)"
guard let data = str.data(using: .utf8) else {
throw Exception.Authentication.unableToEncodeCredentials
}
return Authentication(prefix: "Basic", value: data.base64EncodedString(), description: "credential")
}
}
|
mit
|
4e1d09722f17d9115abcee87995cf426
| 36.322034 | 108 | 0.652134 | 4.915179 | false | false | false | false |
alexbasson/swift-experiment
|
SwiftExperimentTests/Presenters/MoviesPresenterSpec.swift
|
1
|
1560
|
import Quick
import Nimble
import SwiftExperiment
class MoviesPresenterSpec: QuickSpec {
override func spec() {
var subject: MoviesPresenter!
let cellPresenterDataSource = MockCellPresenterDataSource()
beforeEach {
cellPresenterDataSource.resetSentMessages()
subject = MoviesPresenter(cellPresenterDataSource: cellPresenterDataSource)
}
describe("presentMoviesInTableView") {
let movie0 = Movie(title: "Ratatouille")
let movie1 = Movie(title: "Cars")
var tableView: UITableView!
beforeEach {
tableView = UITableView()
subject.present(movies: [movie0, movie1], tableView: tableView)
}
it("messages the cell presenter data source to display cell presenters in a table view") {
expect(cellPresenterDataSource.display.wasReceived).to(beTrue())
}
it("passes to the cell presenter data source an array of cell presenters that have been configured with the movies") {
let cellPresenters = cellPresenterDataSource.display.params.cellPresenters
let cellPresenter0 = cellPresenters[0] as! MovieCellPresenter
let cellPresenter1 = cellPresenters[1] as! MovieCellPresenter
expect(cellPresenter0.movie).to(equal(movie0))
expect(cellPresenter1.movie).to(equal(movie1))
}
it("passes to the cell presenter data source the table view") {
expect(cellPresenterDataSource.display.params.tableView!).to(beIdenticalTo(tableView))
}
}
}
}
|
mit
|
e54924b880bdf7a99d9a812220472449
| 36.142857 | 126 | 0.683974 | 4.770642 | false | false | false | false |
DiabetesCompass/Diabetes_Compass
|
BGCompass/BGReadingLightsHelper.swift
|
1
|
5231
|
//
// BGReadingLightsHelper.swift
// BGCompass
//
// Created by Steve Baker on 2/5/17.
// Copyright © 2017 Clif Alferness. All rights reserved.
//
import Foundation
/** This class returns [BGReadingLight] for use by Swift unit tests.
*/
class BGReadingLightsHelper: NSObject {
/**
- returns: an array of BGReadingLight
readings are one day apart, ending on endDate
Method name describes mg/dL, method converts units to mmol/L for BGReading.quantity
*/
class func bgReadingLights135(endDate: Date) -> [BGReadingLight] {
var bgReadingLights: [BGReadingLight] = []
let date = Date()
let numberOfReadings = 101;
for i in 0..<numberOfReadings {
// start with earliest reading
let timeInterval = -Double(Int(SECONDS_PER_DAY) * ((numberOfReadings - 1) - i))
let timeStamp = date.addingTimeInterval(timeInterval)
let quantity = Float(135.0) / MG_PER_DL_PER_MMOL_PER_L
let bgReadingLight = BGReadingLight(timeStamp: timeStamp, quantity: quantity)
bgReadingLights.append(bgReadingLight)
}
return bgReadingLights
}
/** Method name describes mg/dL, method converts units to mmol/L for BGReading.quantity
- returns: an array of BGReadingLight
readings are one day apart, ending on endDate
*/
class func bgReadingsLightsAlternating135and170(endDate: Date) -> [BGReadingLight] {
var bgReadingLights: [BGReadingLight] = []
let date = Date()
let numberOfReadings = 101;
for i in 0..<numberOfReadings {
// start with earliest reading
let timeInterval = -Double(Int(SECONDS_PER_DAY) * ((numberOfReadings - 1) - i))
let timeStamp = date.addingTimeInterval(timeInterval)
var quantity: Float = 0.0
// use modulo operator %
if (i % 2 == 0) {
// i is even
quantity = 135.0 / MG_PER_DL_PER_MMOL_PER_L
} else {
quantity = 170.0 / MG_PER_DL_PER_MMOL_PER_L
}
let bgReadingLight = BGReadingLight(timeStamp: timeStamp, quantity: quantity)
bgReadingLights.append(bgReadingLight)
}
return bgReadingLights
}
/// Method name describes mg/dL, method converts units to mmol/L for BGReading.quantity
class func bgReadingLights30at150then70at50(endDate: Date) -> [BGReadingLight] {
var bgReadingLights: [BGReadingLight] = []
let date = Date()
let numberOfReadings = 100;
for i in 0..<numberOfReadings {
// start with earliest reading
let timeInterval = -Double(Int(SECONDS_PER_DAY) * ((numberOfReadings - 1) - i))
let timeStamp = date.addingTimeInterval(timeInterval)
var quantity: Float = 0.0
// use modulo operator %
if (i < 30) {
quantity = 150.0 / MG_PER_DL_PER_MMOL_PER_L
} else {
quantity = 50.0 / MG_PER_DL_PER_MMOL_PER_L
}
let bgReadingLight = BGReadingLight(timeStamp: timeStamp, quantity: quantity)
bgReadingLights.append(bgReadingLight)
}
return bgReadingLights
}
/// Method name describes mg/dL, method converts units to mmol/L for BGReading.quantity
class func bgReadingLights50at150then50at50(endDate: Date) -> [BGReadingLight] {
var bgReadingLights: [BGReadingLight] = []
let date = Date()
let numberOfReadings = 100;
for i in 0..<numberOfReadings {
// start with earliest reading
let timeInterval = -Double(Int(SECONDS_PER_DAY) * ((numberOfReadings - 1) - i))
let timeStamp = date.addingTimeInterval(timeInterval)
var quantity: Float = 0.0
// use modulo operator %
if (i < 50) {
quantity = 150.0 / MG_PER_DL_PER_MMOL_PER_L
} else {
quantity = 50.0 / MG_PER_DL_PER_MMOL_PER_L
}
let bgReadingLight = BGReadingLight(timeStamp: timeStamp, quantity: quantity)
bgReadingLights.append(bgReadingLight)
}
return bgReadingLights
}
/// Method name describes mg/dL, method converts units to mmol/L for BGReading.quantity
class func bgReadingLights50at50then50at150(endDate: Date) -> [BGReadingLight] {
var bgReadingLights: [BGReadingLight] = []
let date = Date()
let numberOfReadings = 100;
for i in 0..<numberOfReadings {
// start with earliest reading
let timeInterval = -Double(Int(SECONDS_PER_DAY) * ((numberOfReadings - 1) - i))
let timeStamp = date.addingTimeInterval(timeInterval)
var quantity: Float = 0.0
// use modulo operator %
if (i < 50) {
quantity = 50.0 / MG_PER_DL_PER_MMOL_PER_L
} else {
quantity = 150.0 / MG_PER_DL_PER_MMOL_PER_L
}
let bgReadingLight = BGReadingLight(timeStamp: timeStamp, quantity: quantity)
bgReadingLights.append(bgReadingLight)
}
return bgReadingLights
}
}
|
mit
|
99f3a76383f685c1fd3ac4a37f301eaf
| 33.866667 | 91 | 0.598853 | 4.150794 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS Tests/ConversationListBottomBarControllerTests.swift
|
1
|
4046
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
class MockConversationListBottomBarDelegate: NSObject, ConversationListBottomBarControllerDelegate {
func conversationListBottomBar(_ bar: ConversationListBottomBarController, didTapButtonWithType buttonType: ConversationListButtonType) {
switch buttonType {
case .archive:
self.archiveButtonTapCount += 1
case .startUI:
self.startUIButtonCallCount += 1
case .list:
self.listButtonCallCount += 1
case .folder:
self.folderButtonTapCount += 1
}
}
var startUIButtonCallCount: Int = 0
var archiveButtonTapCount: Int = 0
var listButtonCallCount: Int = 0
var folderButtonTapCount: Int = 0
}
final class ConversationListBottomBarControllerTests: ZMSnapshotTestCase {
var sut: ConversationListBottomBarController!
var mockDelegate: MockConversationListBottomBarDelegate!
override func setUp() {
super.setUp()
snapshotBackgroundColor = UIColor(white: 0.2, alpha: 1) // In order to make the separator more visible
accentColor = .brightYellow
mockDelegate = MockConversationListBottomBarDelegate()
UIView.performWithoutAnimation({
self.sut = ConversationListBottomBarController()
self.sut.delegate = self.mockDelegate
// SUT has a priority 750 height constraint. fix its height first
NSLayoutConstraint.activate([
sut.view.heightAnchor.constraint(equalToConstant: 56)
])
})
}
override func tearDown() {
sut = nil
mockDelegate = nil
super.tearDown()
}
func testThatItRendersTheBottomBarCorrectlyInInitialState() {
// then
verifyInAllPhoneWidths(view: sut.view)
}
func testThatItHidesTheContactsTitleAndShowsArchivedButtonWhen_ShowArchived_IsSetToYes() {
// when
sut.showArchived = true
// then
verifyInAllPhoneWidths(view: sut.view)
}
func testThatItShowsTheContactsTitleAndHidesTheArchivedButtonWhen_ShowArchived_WasSetToYesAndIsSetToNo() {
// given
accentColor = .strongBlue // To make the snapshot distinguishable from the inital state
sut.showArchived = true
// when
sut.showArchived = false
// then
verifyInAllPhoneWidths(view: sut.view)
}
func testThatItCallsTheDelegateWhenTheContactsButtonIsTapped() {
// when
sut.startTabView.button.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(mockDelegate.archiveButtonTapCount, 0)
}
func testThatItCallsTheDelegateWhenTheArchivedButtonIsTapped() {
// when
sut.archivedTabView.button.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(mockDelegate.archiveButtonTapCount, 1)
}
func testThatItCallsTheDelegateWhenTheListButtonIsTapped() {
// when
sut.listTabView.button.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(mockDelegate.listButtonCallCount, 1)
}
func testThatItCallsTheDelegateWhenTheFolderButtonIsTapped() {
// when
sut.folderTabView.button.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(mockDelegate.folderButtonTapCount, 1)
}
}
|
gpl-3.0
|
0f78ca1afb50a01d441a8b4dbb30c559
| 30.858268 | 141 | 0.688581 | 4.94621 | false | true | false | false |
Sage-Bionetworks/BridgeAppSDK
|
BridgeAppSDK/SBAScheduledActivityManager.swift
|
1
|
58589
|
//
// SBAScheduledActivityManager.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
import BridgeSDK
/**
Enum defining the default sections used by the `SBAScheduledActivityManager` to display
scheduled activities.
*/
public enum SBAScheduledActivitySection {
case none
case expiredYesterday
case today
case keepGoing
case tomorrow
case comingUp
}
public enum SBAScheduleLoadState {
case firstLoad
case cachedLoad
case fromServerWithFutureOnly
case fromServerForFullDateRange
}
/**
UI Delegate for the data source.
*/
public protocol SBAScheduledActivityManagerDelegate: SBAAlertPresenter {
/**
Callback that a reload of the scheduled activities has finished.
*/
func reloadFinished(_ sender: Any?)
}
/**
Default data source handler for scheduled activities. This manager is intended to get `SBBScheduledActivity`
objects from the Bridge server and can present the associated tasks.
*/
open class SBABaseScheduledActivityManager: NSObject, ORKTaskViewControllerDelegate {
/**
The delegate is required for presenting tasks and refreshing the UI.
*/
open weak var delegate: SBAScheduledActivityManagerDelegate?
/**
`SBABridgeInfo` instance. By default, this is the shared bridge info defined by the app delegate.
*/
open var bridgeInfo: SBABridgeInfo! {
return _bridgeInfo
}
fileprivate var _bridgeInfo: SBABridgeInfo!
/**
`SBAUserWrapper` instance. By default, this is the shared user defined by the app delegate.
*/
open var user: SBAUserWrapper! {
return _user
}
fileprivate var _user: SBAUserWrapper!
// MARK: initializers
public override init() {
super.init()
commonInit()
}
public init(delegate: SBAScheduledActivityManagerDelegate?) {
super.init()
self.delegate = delegate
commonInit()
}
func commonInit() {
guard let appDelegate = UIApplication.shared.delegate as? SBAAppInfoDelegate else { return }
_bridgeInfo = appDelegate.bridgeInfo
_user = appDelegate.currentUser
self.daysAhead = self.bridgeInfo.cacheDaysAhead
self.daysBehind = self.bridgeInfo.cacheDaysBehind
}
// MARK: Data source management
/**
By default, this is an array of the activities fetched by the call to the server in `reloadData`.
*/
open var activities: [SBBScheduledActivity] = []
/**
Number of days ahead to fetch
*/
open var daysAhead: Int!
/**
Number of days behind to fetch
*/
open var daysBehind: Int!
/**
A predicate that can be used to evaluate whether or not a schedule should be included.
This can include block predicates and is evaluated on a `SBBScheduledActivity` object.
Default == `true`
*/
open var scheduleFilterPredicate: NSPredicate = NSPredicate(value: true)
// MARK: SBAScheduledActivityDataSource
/**
Reload the data by calling the `SBABridgeManager` and fetching changes to the scheduled activities.
*/
@objc open func reloadData() {
// Fetch all schedules (including completed)
let now = Date().startOfDay()
let fromDate = now.addingNumberOfDays(-1 * daysBehind)
let toDate = now.addingNumberOfDays(daysAhead + 1)
loadScheduledActivities(from: fromDate, to: toDate)
}
/**
Flush the loading state and data stored in memory.
*/
open func resetData() {
_loadingState = .firstLoad
_loadingBlocked = false
self.activities.removeAll()
}
/**
Load a given range of schedules
*/
open func loadScheduledActivities(from fromDate: Date, to toDate: Date) {
// Exit early if already reloading activities. This can happen if the user flips quickly back and forth from
// this tab to another tab.
if (_reloading) {
_loadingBlocked = true
return
}
_loadingBlocked = false
_reloading = true
if _loadingState == .firstLoad {
// If launching, then load from cache *first* before looking to the server
// This will ensure that the schedule loads quickly (if not first time) and
// will still load from server to get anything that may have changed dues to
// added schedules or whatnot. Note: for this project, this is not expected
// to yeild any different info, but the project could change. syoung 07/17/2017
_loadingState = .cachedLoad
SBABridgeManager.fetchAllCachedScheduledActivities() { [weak self] (obj, _) in
self?.handleLoadedActivities(obj as? [SBBScheduledActivity], from: fromDate, to: toDate)
}
}
else {
self.loadFromServer(from: fromDate, to: toDate)
}
}
fileprivate func loadFromServer(from fromDate: Date, to toDate: Date) {
var loadStart = fromDate
// First load the future and *then* look to the server for the past schedules.
// This will result in a faster loading for someone who is logging in.
let todayStart = Date().startOfDay()
if shouldLoadFutureFirst && fromDate < todayStart && _loadingState == .cachedLoad {
_loadingState = .fromServerWithFutureOnly
loadStart = todayStart
}
else {
_loadingState = .fromServerForFullDateRange
}
fetchScheduledActivities(from: loadStart, to: toDate) { [weak self] (activities, _) in
self?.handleLoadedActivities(activities, from: fromDate, to: toDate)
}
}
fileprivate func handleLoadedActivities(_ scheduledActivities: [SBBScheduledActivity]?, from fromDate: Date, to toDate: Date) {
if _loadingState == .firstLoad {
// If the loading state is first load then that means the data has been reset so we should ignore the response
_reloading = false
if _loadingBlocked {
loadScheduledActivities(from: fromDate, to: toDate)
}
return
}
DispatchQueue.main.async {
if let scheduledActivities = self.sortActivities(scheduledActivities) {
self.load(scheduledActivities: scheduledActivities)
}
if self._loadingState == .fromServerForFullDateRange {
// If the loading state is for the full range, then we are done.
self._reloading = false
}
else {
// Otherwise, load more range from the server
self.loadFromServer(from: fromDate, to: toDate)
}
}
}
fileprivate func fetchScheduledActivities(from fromDate: Date, to toDate: Date, completion: @escaping ([SBBScheduledActivity]?, Error?) -> Swift.Void) {
SBABridgeManager.fetchScheduledActivities(from: fromDate, to: toDate) {(obj, error) in
completion(obj as? [SBBScheduledActivity], error)
}
}
open func sortActivities(_ scheduledActivities: [SBBScheduledActivity]?) -> [SBBScheduledActivity]? {
guard (scheduledActivities?.count ?? 0) > 0 else { return nil }
return scheduledActivities!.sorted(by: { (scheduleA, scheduleB) -> Bool in
return scheduleA.scheduledOn.compare(scheduleB.scheduledOn) == .orderedAscending
})
}
/**
When loading schedules, should the manager *first* load all the future schedules.
If true, this will result in a staged call to the server, where first, the future
is loaded and then the server request is made to load past schedules. This will
result in a faster loading but may result in undesired behavior for a manager
that relies upon the past results to build the displayed activities.
*/
public var shouldLoadFutureFirst = true
/**
State management for what the current loading state is. This is used to
pre-load from cache before going to the server for updates.
*/
public var loadingState: SBAScheduleLoadState {
return _loadingState
}
fileprivate var _loadingState: SBAScheduleLoadState = .firstLoad
/**
State management for whether or not the schedules are reloading.
*/
public var isReloading: Bool {
return _reloading
}
fileprivate var _reloading: Bool = false
fileprivate var _loadingBlocked: Bool = false
// MARK: Data handling
/**
Called once the response from the server returns the scheduled activities.
@param scheduledActivities The list of activities returned by the service.
*/
open func load(scheduledActivities: [SBBScheduledActivity]) {
// schedule notifications
setupNotifications(for: scheduledActivities)
// Filter the scheduled activities to only include those that *this* version of the app is designed
// to be able to handle. Currently, that means only taskReference activities with an identifier that
// maps to a known task.
self.activities = filteredSchedules(scheduledActivities: scheduledActivities)
// reload table
self.delegate?.reloadFinished(self)
// preload all the surveys so that they can be accessed offline
if _loadingState == .fromServerForFullDateRange {
for schedule in scheduledActivities {
if schedule.activity.survey != nil {
SBABridgeManager.loadSurvey(schedule.activity.survey!, completion:{ (_, _) in
})
}
}
}
}
/**
Filter the scheduled activities to only include those that *this* version of the app is designed
to be able to handle. Currently, that means only taskReference activities with an identifier that
maps to a known task.
@param scheduledActivities The list of activities returned by the service.
@return The filtered list of activities
*/
open func filteredSchedules(scheduledActivities: [SBBScheduledActivity]) -> [SBBScheduledActivity] {
if _loadingState == .fromServerWithFutureOnly {
// The future only will be in a state where we already have the cached data,
// And we will probably just be appending new data onto the cached data
let filteredActivities = scheduledActivities.filter({ (activity) in
return !self.activities.contains(where: { (existingActivity) -> Bool in
return existingActivity.guid == activity.guid
})
})
return self.activities.sba_appending(contentsOf: filteredActivities)
}
return scheduledActivities.filter({ (schedule) -> Bool in
return bridgeInfo.taskReferenceForSchedule(schedule) != nil &&
self.scheduleFilterPredicate.evaluate(with: schedule)
})
}
/**
Called on load to setup notifications for the returned scheduled activities.
@param scheduledActivities The list of activities for which to schedule notifications
*/
@objc(setupNotificationsForScheduledActivities:)
open func setupNotifications(for scheduledActivities: [SBBScheduledActivity]) {
// schedule notifications
SBANotificationsManager.shared.setupNotifications(for: scheduledActivities)
}
/**
By default, a scheduled activity is available if it is available now or
it is completed.
@param schedule The schedule to check
@return `YES` if the task can be run and `NO` if the task is scheduled for the future or expired.
*/
open func isAvailable(schedule: SBBScheduledActivity) -> Bool {
return schedule.isNow || schedule.isCompleted
}
/**
If a schedule is unavailable, then the user is shown an alert explaining when it will
become available.
@param schedule The schedule to check
@return The message to display in an alert for a schedule that is not currently available.
*/
open func messageForUnavailableSchedule(_ schedule: SBBScheduledActivity) -> String {
var scheduledTime: String!
if schedule.isToday {
scheduledTime = schedule.scheduledTime
}
else if schedule.isTomorrow {
scheduledTime = Localization.localizedString("SBA_ACTIVITY_TOMORROW")
}
else {
scheduledTime = DateFormatter.localizedString(from: schedule.scheduledOn, dateStyle: .medium, timeStyle: .none)
}
return Localization.localizedStringWithFormatKey("SBA_ACTIVITY_SCHEDULE_MESSAGE", scheduledTime)
}
// MARK: Task management
/**
Get the scheduled activity that is associated with this task view controller.
@param taskViewController The task view controller being displayed.
@return The schedule associated with this task view controller (if available)
*/
@objc(scheduledActivityForTaskViewController:)
open func scheduledActivity(for taskViewController: ORKTaskViewController) -> SBBScheduledActivity? {
guard let vc = taskViewController as? SBATaskViewController
else {
return nil
}
return scheduledActivity(with: vc.scheduleIdentifier)
}
/**
Get the scheduled activity that is associated with this schedule identifier.
@param scheduleIdentifier The schedule identifier that was used to start the task.
@return The schedule associated with this task view controller (if available)
*/
@objc(scheduledActivityWithScheduleIdentifier:)
open func scheduledActivity(with scheduleIdentifier: String?) -> SBBScheduledActivity? {
guard let scheduleIdentifier = scheduleIdentifier
else {
return nil
}
return activities.sba_find({ $0.activity.guid == scheduleIdentifier })
}
/**
Get the scheduled activity that is associated with this task identifier.
@param taskIdentifier The task identifier for a given schedule
@return The task identifier associated with the given schedule (if available)
*/
@objc(scheduledActivityForTaskIdentifier:)
open func scheduledActivity(for taskIdentifier: String) -> SBBScheduledActivity? {
return activities.sba_find({ $0.activityIdentifier == taskIdentifier })
}
// MARK: ORKTaskViewControllerDelegate
public let offMainQueue = DispatchQueue(label: "org.sagebase.BridgeAppSDK.SBAScheduledActivityManager")
open func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
// Re-enable the passcode lock. This can be disabled by the display of an active step.
SBAAppDelegate.shared?.disablePasscodeLock = false
// syoung 07/11/2017 Kludgy work-around for locking interface orientation following showing a
// view controller that requires landscape orientation
SBAAppDelegate.shared?.resetOrientation()
// default behavior is to only record the task results if the task completed
if reason == ORKTaskViewControllerFinishReason.completed {
recordTaskResults_async(for: taskViewController)
}
else {
taskViewController.task?.resetTrackedDataChanges()
}
taskViewController.dismiss(animated: true) {
self.offMainQueue.async {
self.deleteOutputDirectory(for: taskViewController)
self.debugPrintSandboxFiles()
}
}
}
open func taskViewController(_ taskViewController: ORKTaskViewController, stepViewControllerWillAppear stepViewController: ORKStepViewController) {
// If cancel is disabled then hide on all but the first step
if let step = stepViewController.step, shouldHideCancel(for: step, taskViewController: taskViewController) {
stepViewController.cancelButtonItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
}
// If it is the last step in the task *and* it's a completion step (not a step
// that might change the results) then record the task result. This allows the
// results to be recorded and updated prior to ending the task and ensures that
// even if the user forgets to tap the "Done" button, their results will be
// recorded.
if let step = stepViewController.step, let task = taskViewController.task,
task.isCompletion(step: step, with: taskViewController.result) {
recordTaskResults_async(for: taskViewController)
}
}
open func taskViewController(_ taskViewController: ORKTaskViewController, viewControllerFor step: ORKStep) -> ORKStepViewController? {
// If this is the first step in an activity then look to see if there is a custom intro view controller
if step.stepViewControllerClass() == ORKInstructionStepViewController.self,
let task = taskViewController.task as? ORKOrderedTask, task.index(of: step) == 0,
let schedule = self.scheduledActivity(for: taskViewController),
let taskRef = bridgeInfo.taskReferenceForSchedule(schedule),
let vc = instantiateActivityIntroductionStepViewController(for: schedule, step: step, taskRef: taskRef) {
return vc
}
// If the default view controller for this step is an `ORKInstructionStepViewController` (and not a subclass)
// then replace that implementation with the one from this framework.
if step.stepViewControllerClass() == ORKInstructionStepViewController.self, let task = taskViewController.task {
return instantiateInstructionStepViewController(for: step, task: task, result: taskViewController.result)
}
// If the default view controller for this step is an `ORKCompletionStepViewController` (and not a subclass)
// then replace that implementation with the one from this framework.
if step.stepViewControllerClass() == ORKCompletionStepViewController.self, let task = taskViewController.task {
return instantiateCompletionStepViewController(for: step, task: task, result: taskViewController.result)
}
// If this is a permissions step then return a page step view controller instead.
// This will display a paged view controller. Including at this level b/c we are trying to keep
// ResearchUXFactory agnostic to the UI that Sage uses for our apps. syoung 05/30/2017
if step is SBAPermissionsStep {
return ORKPageStepViewController(step: step)
}
// By default, return nil
return nil
}
// MARK: Convenience methods
/**
Method for creating the task view controller. This is marked final with the intention that any class
that has a custom implementation should override one of the protected subclass methods used to
create the view controller.
@param schedule The schedule to use to create the task
@return The created task view controller
*/
@objc(createTaskViewControllerForSchedule:)
public final func createTaskViewController(for schedule: SBBScheduledActivity) -> SBATaskViewController? {
let (inTask, inTaskRef) = createTask(for: schedule)
guard let task = inTask, let taskRef = inTaskRef else { return nil }
let taskViewController = instantiateTaskViewController(for: schedule, task: task, taskRef: taskRef)
setup(taskViewController: taskViewController, schedule: schedule, taskRef: taskRef)
return taskViewController
}
// MARK: Protected subclass methods
/**
Delete the output directory for a task once completed.
@param taskViewController The task view controller being displayed.
*/
@objc(deleteOutputDirectoryForTaskViewController:)
open func deleteOutputDirectory(for taskViewController: ORKTaskViewController) {
guard let outputDirectory = taskViewController.outputDirectory else { return }
do {
try FileManager.default.removeItem(at: outputDirectory)
} catch let error {
print("Error removing ResearchKit output directory: \(error.localizedDescription)")
debugPrint("\tat: \(outputDirectory)")
}
}
fileprivate func debugPrintSandboxFiles() {
#if DEBUG
DispatchQueue.main.async {
let fileMan = FileManager.default
let homeDir = URL.init(string: NSHomeDirectory())
let directoryEnumerator = fileMan.enumerator(at: homeDir!, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey, URLResourceKey.fileSizeKey], options: FileManager.DirectoryEnumerationOptions.init(rawValue:0), errorHandler: nil)
var mutableFileInfo = Dictionary<URL, Int>()
while let originalURL = directoryEnumerator?.nextObject() as? URL {
let fileURL = originalURL.resolvingSymlinksInPath();
do {
let urlResourceValues = try fileURL.resourceValues(forKeys: [URLResourceKey.isDirectoryKey, URLResourceKey.fileSizeKey])
if !urlResourceValues.isDirectory! {
let fileSizeOrNot = urlResourceValues.fileSize ?? -1
mutableFileInfo[fileURL] = fileSizeOrNot
}
} catch let error {
debugPrint("Error: \(error)")
}
}
debugPrint("\(mutableFileInfo.count) files left in our sandbox:")
for fileURL in mutableFileInfo.keys {
let fileSize = mutableFileInfo[fileURL]
debugPrint("\(fileURL.path) size:\(String(describing: fileSize))")
};
}
#endif
}
/**
Should the cancel button be hidden for this step?
@param step The step to be displayed
@param taskViewController The task view controller being displayed.
@return `YES` if the cancel button should be hidden, otherwise `NO`
*/
@objc(shouldHideCancelForStep:taskViewController:)
open func shouldHideCancel(for step: ORKStep, taskViewController: ORKTaskViewController) -> Bool {
// Return false if cancel is *not* disabled
guard let schedule = scheduledActivity(for: taskViewController),
let taskRef = bridgeInfo.taskReferenceForSchedule(schedule) , taskRef.cancelDisabled
else {
return false
}
// If the task does not respond then assume that cancel should be hidden for all steps
guard let task = taskViewController.task as? SBATaskExtension
else {
return true
}
// Otherwise, do not disable the first step IF and ONLY IF there are more than 1 steps.
return task.stepCount() == 1 || task.index(of: step) > 0;
}
/**
Whether or not the task should be enabled. This is different from whether or not a task is "available"
in that it *only* applies to activities that are "greyed out" because they are expired, or because
the task does not allow multiple runs of a completed activity.
@param schedule The schedule to check
@return `YES` if this schedule is displayed as `enabled` (now or future)
*/
@objc(shouldShowTaskForSchedule:)
open func shouldShowTask(for schedule: SBBScheduledActivity) -> Bool {
// Allow user to perform a task again as long as the task is not expired
guard let taskRef = bridgeInfo.taskReferenceForSchedule(schedule) else { return false }
return !schedule.isExpired && (!schedule.isCompleted || taskRef.allowMultipleRun)
}
/**
Instantiate the appropriate task view controller.
@param schedule The schedule associated with this task
@param task The task to use to instantiate the view controller
@param taskRef The task reference associated with this task
@return A new instance of a `SBATaskReference`
*/
open func instantiateTaskViewController(for schedule: SBBScheduledActivity, task: ORKTask, taskRef: SBATaskReference) -> SBATaskViewController {
let taskViewController = SBATaskViewController(task: task, taskRun: nil)
// Because of a bug in ResearchKit that looks at the _defaultResultSource ivar rather than
// the property, this will always return the view controller as the result source.
// This allows us to attach a different source. syoung 07/10/2017
taskViewController.defaultResultSource = createTaskResultSource(for: schedule, task: taskViewController.task!, taskRef: taskRef)
return taskViewController
}
open func instantiateActivityIntroductionStepViewController(for schedule: SBBScheduledActivity, step: ORKStep, taskRef: SBATaskReference) -> SBAActivityInstructionStepViewController? {
let vc = SBAActivityInstructionStepViewController(step: step)
vc.schedule = schedule
vc.taskReference = taskRef
return vc
}
open func instantiateInstructionStepViewController(for step: ORKStep, task: ORKTask, result: ORKTaskResult) -> ORKStepViewController? {
let vc = SBAInstructionStepViewController(step: step, result: result)
if let progress = task.progress?(ofCurrentStep: step, with: result) {
vc.stepNumber = progress.current + 1
vc.stepTotal = progress.total
}
return vc
}
open func instantiateGenericStepViewController(for step: ORKStep, task: ORKTask, result: ORKTaskResult) -> ORKStepViewController? {
let vc = SBAGenericStepViewController(step: step, result: result)
if let progress = task.progress?(ofCurrentStep: step, with: result) {
vc.stepCount = Int(progress.total)
vc.stepIndex = Int(progress.current)
}
return vc
}
open func instantiateCompletionStepViewController(for step: ORKStep, task: ORKTask, result: ORKTaskResult) -> ORKStepViewController? {
let vc = SBACompletionStepViewController(step: step)
return vc
}
/**
Create the task and task reference for the given schedule.
@param schedule The schedule associated with this task
@return task The task instantiated from this schedule
taskRef The task reference associated with this task
*/
open func createTask(for schedule: SBBScheduledActivity) -> (task: ORKTask?, taskRef: SBATaskReference?) {
guard let taskRef = bridgeInfo.taskReferenceForSchedule(schedule) else { return (nil, nil) }
// get a factory for this task reference
let factory = createFactory(for: schedule, taskRef: taskRef)
SBAInfoManager.shared.defaultSurveyFactory = factory
// transform the task reference into a task using the given factory
let task = taskRef.transformToTask(with: factory, isLastStep: true)
if let surveyTask = task as? SBASurveyTask {
surveyTask.title = schedule.activity.label
}
return (task, taskRef)
}
/**
Create a task result source for the given schedule and task.
@param schedule The schedule associated with this task
@param task The task instantiated from this schedule
@param taskRef The task reference associated with this task
@return The result source to attach to this task (if any)
*/
open func createTaskResultSource(for schedule:SBBScheduledActivity, task: ORKTask, taskRef: SBATaskReference? = nil) -> ORKTaskResultSource? {
// Look at top-level steps for a subtask that might have its own schedule
var sources: [SBATaskResultSource] = []
if let navTask = task as? SBANavigableOrderedTask {
for step in navTask.steps {
if let subtaskStep = step as? SBASubtaskStep,
let taskId = subtaskStep.taskIdentifier,
let subschedule = self.scheduledActivity(for: taskId),
let source = self.createTaskResultSource(for: subschedule, task: subtaskStep.subtask) as? SBATaskResultSource {
sources.append(source)
}
}
}
// Look for client data that can be used to generate a result source
let answerMap: [String: Any]? = {
if let array = schedule.clientData as? [[String : Any]] {
return array.last
}
return schedule.clientData as? [String : Any]
}()
let hasTrackedSelection: Bool = {
guard let collection = (task as? SBANavigableOrderedTask)?.conditionalRule as? SBATrackedDataObjectCollection
else {
return false
}
return collection.dataStore.selectedItems != nil
}()
if sources.count > 0 {
// If the sources count is greater than 0 then return a combo result source (even if this schedule
// does not have an answer map
return SBAComboTaskResultSource(task: task, answerMap: answerMap ?? [:], sources: sources)
}
else if answerMap != nil || hasTrackedSelection {
// Otherwise, if the answer map is non-nil, or there is a tracked data collection
// then return a result source for this task specifically
return SBASurveyTaskResultSource(task: task, answerMap: answerMap ?? [:])
}
else {
// Finally, there is no result source applicable to this task so return nil
return nil
}
}
/**
Create a factory to use when creating a survey or active task. Override to create a custom
survey factory that can be used to vend custom steps.
@param schedule The schedule associated with this task
@param taskRef The task reference associated with this task
@return The factory to use for creating the task
*/
open func createFactory(for schedule: SBBScheduledActivity, taskRef: SBATaskReference) -> SBASurveyFactory {
return SBASurveyFactory()
}
/**
Once the task view controller is instantiated, set up the delegate and schedule identifier.
Override to setup any custom handling associated with this view controller.
@param taskViewController The task view controller to be displayed.
@param schedule The schedule associated with this task
@param taskRef The task reference associated with this task
*/
open func setup(taskViewController: SBATaskViewController, schedule: SBBScheduledActivity, taskRef: SBATaskReference) {
taskViewController.scheduleIdentifier = schedule.activity.guid
taskViewController.delegate = self
}
/**
Subclass can override to provide custom implementation. By default, will return `YES`
unless this is a survey with an error or the results have already been uploaded.
@param schedule The schedule associated with this task
@param taskViewController The task view controller that was displayed.
*/
@objc(shouldRecordResultForSchedule:taskViewController:)
open func shouldRecordResult(for schedule: SBBScheduledActivity, taskViewController: ORKTaskViewController) -> Bool {
// Check if the flag has been set that the results are already being uploaded.
// This allows tasks to be uploaded with the call to task finished *or* in the previous
// step if the last step is a completion step, but will keep the results from being
// uploaded more than once.
if let vc = taskViewController as? SBATaskViewController, vc.hasUploadedResults {
return false
}
// Look to see if this is an online survey which has failed to download
// In this case, do not mark on the server as completed.
if let task = taskViewController.task as? SBASurveyTask, task.error != nil {
return false
}
return true
}
/**
Method to move upload to background thread.
*/
func recordTaskResults_async(for taskViewController: ORKTaskViewController) {
// Check if the results of this survey should be uploaded
guard let schedule = scheduledActivity(for: taskViewController),
let inTask = taskViewController.task,
shouldRecordResult(for: schedule, taskViewController:taskViewController)
else {
return
}
// Mark the flag that the results are being uploaded for this task
if let vc = taskViewController as? SBATaskViewController {
vc.hasUploadedResults = true
}
let task = ((inTask as? NSCopying)?.copy(with: nil) as? ORKTask) ?? inTask
let result = taskViewController.result.copy() as! ORKTaskResult
let finishedOn = (taskViewController as? SBATaskViewController)?.finishedOn
self.offMainQueue.async {
self.recordTaskResults(for: schedule, task: task, result: result, finishedOn: finishedOn)
}
}
@available(*, unavailable, message:"Use `recordTaskResults(for:task:result:finishedOn:)` instead.")
open func recordTaskResults(for taskViewController: ORKTaskViewController) {
}
/**
This method is called during task finish to handle data sync to the Bridge server.
It includes updating tracked data changes (such as data groups), marking the schedule
as finished and archiving the results.
@param schedule The schedule associated with this task
@param task The task being recorded. This is the main task and may include subtasks.
@param result The task result. This is the main task result and may include subtask results.
@param finishedOn The timestamp to use for when the task was finished.
*/
@objc(recordTaskResultsForSchedule:task:result:finishedOn:)
open func recordTaskResults(for schedule: SBBScheduledActivity, task: ORKTask, result: ORKTaskResult, finishedOn: Date?) {
// Update any data stores and groups associated with this task
task.commitTrackedDataChanges(user: user,
taskResult: result,
completion:handleDataGroupsUpdate)
// Archive the results
let results = activityResults(for: schedule, task: task, result:result)
let archives = results.sba_mapAndFilter({ archive(for: $0) })
SBBDataArchive.encryptAndUploadArchives(archives)
// Update the schedule on the server but only if the survey was not ended early
if !didEndSurveyEarly(schedule: schedule, task: task, result: result) {
update(schedule: schedule, task: task, result: result, finishedOn: finishedOn)
}
}
@available(*, unavailable, message:"Use `update(schedule:task:result:finishedOn:)` instead.")
open func update(schedule: SBBScheduledActivity, taskViewController: ORKTaskViewController) {
}
/**
This method is called during task finish to send Bridge server an update to the
schedule with the `finishedOn` and `startedOn` values set to the start/end timestamp
for the task view controller.
@param schedule The schedule associated with this task
@param task The task being recorded. This is the main task and may include subtasks.
@param result The task result. This is the main task result and may include subtask results.
@param finishedOn The timestamp to use for when the task was finished.
*/
open func update(schedule: SBBScheduledActivity, task: ORKTask, result: ORKTaskResult, finishedOn: Date?) {
// Set finish and start timestamps
schedule.finishedOn = finishedOn ?? result.endDate
schedule.startedOn = result.startDate
// Add any additional schedules
var scheduledActivities = [schedule]
// Look at top-level steps for a subtask that might have its own schedule
if let navTask = task as? SBANavigableOrderedTask {
for step in navTask.steps {
if let subtaskStep = step as? SBASubtaskStep, let taskId = subtaskStep.taskIdentifier,
let subschedule = scheduledActivity(for: taskId) , !subschedule.isCompleted {
// If schedule is found then set its start/stop time and add to list to update
subschedule.startedOn = schedule.startedOn
subschedule.finishedOn = schedule.finishedOn
scheduledActivities.append(subschedule)
}
}
}
// Send message to server
sendUpdated(scheduledActivities: scheduledActivities)
}
@available(*, unavailable, message:"Use `didEndSurveyEarly(schedule:task:result:)` instead.")
open func didEndSurveyEarly(schedule: SBBScheduledActivity, taskViewController: ORKTaskViewController) -> Bool {
return false
}
/**
Check to see if the survey was ended early.
@param schedule The schedule associated with this task
@param task The task being recorded. This is the main task and may include subtasks.
@param result The task result. This is the main task result and may include subtask results.
@return Whether or not the survey ended early and should *not* be marked as finished.
*/
open func didEndSurveyEarly(schedule: SBBScheduledActivity, task: ORKTask, result: ORKTaskResult) -> Bool {
if let endResult = result.firstResult( where: { $1 is SBAActivityInstructionResult }) as? SBAActivityInstructionResult,
endResult.didEndSurvey {
return true
}
return false
}
/**
Send message to Bridge server to update the given schedules. This includes both the task
that was completed and any tasks that were performed as a requirement of completion of the
primary task (such as a required one-time survey).
*/
open func sendUpdated(scheduledActivities: [SBBScheduledActivity]) {
SBABridgeManager.updateScheduledActivities(scheduledActivities) {[weak self] (_, _) in
DispatchQueue.main.async {
self?.reloadData()
}
}
}
/**
Expose method for building archive to allow for testing and subclass override. This method is
called during task finish to archive the result for each activity result included in this task.
@param activityResult The `SBAActivityResult` to archive
@return The `SBAActivityArchive` object created with the results for this activity.
*/
@objc(archiveForActivityResult:)
open func archive(for activityResult: SBAActivityResult) -> SBAActivityArchive? {
if let archive = SBAActivityArchive(result: activityResult,
jsonValidationMapping: jsonValidationMapping(activityResult: activityResult)) {
do {
try archive.complete()
return archive
}
catch {}
}
return nil
}
/**
Optional method for inserting json prevalidation for a given activity result.
*/
@objc(jsonValidationMappingForActivityResult:)
open func jsonValidationMapping(activityResult: SBAActivityResult) -> [String: NSPredicate]?{
return nil
}
@available(*, unavailable, message:"Use `activityResults(for:task:result:)` instead.")
open func activityResults(for schedule: SBBScheduledActivity, taskViewController: ORKTaskViewController) -> [SBAActivityResult] {
return []
}
/**
Expose method for building results to allow for testing and subclass override. This method is
called during task finish to parse the `ORKTaskResult` into one or more subtask results. By default,
this method can split a task into different schema tables for upload to the Bridge server.
@param schedule The schedule associated with this task
@param task The task being recorded. This is the main task and may include subtasks.
@param result The task result. This is the main task result and may include subtask results.
@return An array of `SBAActivityResult` that can be used to build an archive.
*/
@objc(activityResultsForSchedule:task:result:)
open func activityResults(for schedule: SBBScheduledActivity, task: ORKTask, result: ORKTaskResult) -> [SBAActivityResult] {
// If no results, return empty array
guard result.results != nil else { return [] }
let taskResult = result
let surveyTask = task as? SBASurveyTask
// Look at the task result start/end date and assign the start/end date for the split result
// based on whether or not the inputDate is greater/less than the comparison date. This way,
// the split result will have a start date that is >= the overall task start date and an
// end date that is <= the task end date.
func outputDate(_ inputDate: Date?, comparison:ComparisonResult) -> Date {
let compareDate = (comparison == .orderedAscending) ? taskResult.startDate : taskResult.endDate
guard let date = inputDate , date.compare(compareDate) == comparison else {
return compareDate
}
return date
}
// Function for creating each split result
func createActivityResult(_ identifier: String, schedule: SBBScheduledActivity, stepResults: [ORKStepResult]) -> SBAActivityResult {
let result = SBAActivityResult(taskIdentifier: identifier, taskRun: taskResult.taskRunUUID, outputDirectory: taskResult.outputDirectory)
result.results = stepResults
result.schedule = schedule
result.startDate = outputDate(stepResults.first?.startDate, comparison: .orderedAscending)
result.endDate = outputDate(stepResults.last?.endDate, comparison: .orderedDescending)
result.schemaRevision = surveyTask?.schemaRevision ?? bridgeInfo.schemaReferenceWithIdentifier(identifier)?.schemaRevision ?? 1
return result
}
// mutable arrays for ensuring all results are collected
var topLevelResults:[ORKStepResult] = result.consolidatedResults()
var allResults:[SBAActivityResult] = []
var dataStores:[SBATrackedDataStore] = []
if let task = task as? SBANavigableOrderedTask {
for step in task.steps {
if let subtaskStep = step as? SBASubtaskStep {
var isDataCollection = false
if let subtask = subtaskStep.subtask as? SBANavigableOrderedTask,
let dataCollection = subtask.conditionalRule as? SBATrackedDataObjectCollection {
// But keep a pointer to the dataStore
dataStores.append(dataCollection.dataStore)
isDataCollection = true
}
if let taskId = subtaskStep.taskIdentifier,
let schemaId = subtaskStep.schemaIdentifier {
// If this is a subtask step with a schemaIdentifier and taskIdentifier
// then split out the result
let (subResults, filteredResults) = subtaskStep.filteredStepResults(topLevelResults)
topLevelResults = filteredResults
// Add filtered results to each collection as appropriate
let subschedule = scheduledActivity(for: taskId) ?? schedule
if subResults.count > 0 {
// add dataStore results but only if this is not a data collection itself
var subsetResults = subResults
if !isDataCollection {
for dataStore in dataStores {
if let momentInDayResults = dataStore.momentInDayResults {
// Mark the start/end date with the start timestamp of the first step
for stepResult in momentInDayResults {
stepResult.startDate = subsetResults.first!.startDate
stepResult.endDate = stepResult.startDate
}
// Add the results at the beginning
subsetResults = momentInDayResults + subsetResults
}
}
}
// create the subresult and add to list
let substepResult: SBAActivityResult = createActivityResult(schemaId, schedule: subschedule, stepResults: subsetResults)
allResults.append(substepResult)
}
}
else if isDataCollection {
// Otherwise, filter out the tracked object collection but do not create results
// because this is tracked via the dataStore
let (_, filteredResults) = subtaskStep.filteredStepResults(topLevelResults)
topLevelResults = filteredResults
}
}
}
}
// If there are any results that were not filtered into a subgroup then include them at the top level
if topLevelResults.filter({ $0.hasResults }).count > 0 {
let topResult = createActivityResult(taskResult.identifier, schedule: schedule, stepResults: topLevelResults)
allResults.insert(topResult, at: 0)
}
return allResults
}
/**
Expose method for handling data groups updating to allow for testing and subclass override.
*/
open func handleDataGroupsUpdate(error: Error?) {
if (error != nil) {
// syoung 09/30/2016 If there was an error with updating the data groups (offline, etc) then
// reset the last tracked survey date to force prompting for the survey again. While this is
// less than ideal UX, it will ensure that there isn't a data sync issue due to the server
// setting data groups and not knowing which are more recent.
SBATrackedDataStore.shared.lastTrackingSurveyDate = nil
}
}
}
extension ORKTask {
public func commitTrackedDataChanges(user: SBAUserWrapper, taskResult: ORKTaskResult, completion: ((Error?) -> Void)?) {
recursiveUpdateTrackedDataStores(shouldCommit: true)
updateDataGroups(user: user, taskResult: taskResult, completion: completion)
}
public func resetTrackedDataChanges() {
recursiveUpdateTrackedDataStores(shouldCommit: false)
}
private func recursiveUpdateTrackedDataStores(shouldCommit: Bool) {
guard let navTask = self as? SBANavigableOrderedTask else { return }
// If this task has a conditional rule then update it
if let collection = navTask.conditionalRule as? SBATrackedDataObjectCollection, collection.dataStore.hasChanges {
if (shouldCommit) {
collection.dataStore.commitChanges()
}
else {
collection.dataStore.reset()
}
}
// recursively search for subtask with a data store
for step in navTask.steps {
if let subtaskStep = step as? SBASubtaskStep {
subtaskStep.subtask.recursiveUpdateTrackedDataStores(shouldCommit: shouldCommit)
}
}
}
private func updateDataGroups(user: SBAUserWrapper, taskResult: ORKTaskResult, completion: ((Error?) -> Void)?) {
let (groups, changed) = self.union(currentGroups: user.dataGroups, with: taskResult)
if changed, let dataGroups = groups {
// If the user groups are changed then update
user.updateDataGroups(dataGroups, completion: completion)
}
else {
// Otherwise call completion
completion?(nil)
}
}
}
/**
syoung 05/03/2017
UI/UX table data source for the presentation used in older apps. We tried to generalize how the schedule
is displayed to the user (using a subclass of `SBAActivityTableViewController`) but doing so forces the model
to work around this design for apps that handle scheduling using a different model.
*/
open class SBAScheduledActivityManager: SBABaseScheduledActivityManager, SBAScheduledActivityDataSource {
/**
Sections to display - this sets up the predicates for filtering activities.
*/
open var sections: [SBAScheduledActivitySection]! {
didSet {
// Filter out any sections that aren't shown
let filters = sections.sba_mapAndFilter({ filterPredicate(for: $0) })
self.scheduleFilterPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: filters)
}
}
override func commonInit() {
super.commonInit()
// Set the default sections
self.sections = [.today, .keepGoing]
}
open func numberOfSections() -> Int {
return sections.count
}
open func numberOfRows(for section: Int) -> Int {
return scheduledActivities(for: section).count
}
open func scheduledActivity(at indexPath: IndexPath) -> SBBScheduledActivity? {
let schedules = scheduledActivities(for: indexPath.section)
guard indexPath.row < schedules.count else {
assertionFailure("Requested row greater than number of rows in section")
return nil
}
return schedules[indexPath.row]
}
open func shouldShowTask(for indexPath: IndexPath) -> Bool {
guard let schedule = scheduledActivity(at: indexPath), shouldShowTask(for: schedule)
else {
return false
}
return true
}
open func didSelectRow(at indexPath: IndexPath) {
// Only if the task was created should something be done.
guard let schedule = scheduledActivity(at: indexPath) else { return }
guard isAvailable(schedule: schedule) else {
// Block performing a task that is scheduled for the future
let message = messageForUnavailableSchedule(schedule)
self.delegate?.showAlertWithOk(title: nil, message: message, actionHandler: nil)
return
}
// If this is a valid schedule then create the task view controller
guard let taskViewController = createTaskViewController(for: schedule)
else {
assertionFailure("Failed to create task view controller for \(schedule)")
return
}
self.delegate?.presentModalViewController(taskViewController, animated: true, completion: nil)
}
open func title(for section: Int) -> String? {
// Always return nil for the first section and if there are no rows in the section
guard scheduledActivities(for: section).count > 0, let scheduledActivitySection = scheduledActivitySection(for: section)
else {
return nil
}
// Return default localized string for each section
switch scheduledActivitySection {
case .expiredYesterday:
return Localization.localizedString("SBA_ACTIVITY_YESTERDAY")
case .today:
return Localization.localizedString("SBA_ACTIVITY_TODAY")
case .keepGoing:
return Localization.localizedString("SBA_ACTIVITY_KEEP_GOING")
case .tomorrow:
return Localization.localizedString("SBA_ACTIVITY_TOMORROW")
case .comingUp:
return Localization.localizedString("SBA_ACTIVITY_COMING_UP")
case .none:
return nil
}
}
/**
Predicate to use to filter the activities for a given table section.
@param tableSection The section index into the table (maps to IndexPath).
@return The predicate to use to filter the table section.
*/
@objc(filterPredicateForTableSection:)
open func filterPredicate(for tableSection: Int) -> NSPredicate? {
guard let section = scheduledActivitySection(for: tableSection) else { return nil }
return filterPredicate(for: section)
}
private func filterPredicate(for section: SBAScheduledActivitySection) -> NSPredicate? {
switch section {
case .expiredYesterday:
// expired yesterday section only showns those expired tasks that are also unfinished
return SBBScheduledActivity.expiredYesterdayPredicate()
case .today:
return NSCompoundPredicate(andPredicateWithSubpredicates: [
NSCompoundPredicate(notPredicateWithSubpredicate: SBBScheduledActivity.optionalPredicate()),
SBBScheduledActivity.availableTodayPredicate()])
case .keepGoing:
// Keep going section includes optional tasks that are either unfinished or were finished today
return NSCompoundPredicate(andPredicateWithSubpredicates: [
SBBScheduledActivity.optionalPredicate(),
SBBScheduledActivity.unfinishedPredicate(),
SBBScheduledActivity.availableTodayPredicate()])
case .tomorrow:
// scheduled for tomorrow only
return SBBScheduledActivity.scheduledTomorrowPredicate()
case .comingUp:
return SBBScheduledActivity.scheduledComingUpPredicate(numberOfDays: self.daysAhead)
case .none:
return nil
}
}
/**
Array of `SBBScheduledActivity` objects for a given table section.
@param tableSection The section index into the table (maps to IndexPath).
@return The list of `SBBScheduledActivity` objects for this table section.
*/
@objc(scheduledActivitiesForTableSection:)
open func scheduledActivities(for tableSection: Int) -> [SBBScheduledActivity] {
guard let predicate = filterPredicate(for: tableSection) else { return [] }
return activities.filter({ predicate.evaluate(with: $0) })
}
private func scheduledActivitySection(for tableSection: Int) -> SBAScheduledActivitySection? {
guard tableSection < sections.count else { return nil }
return sections[tableSection]
}
}
extension ORKTaskResult {
public func firstResult(where evaluate: (_ stepResult: ORKStepResult, _ result: ORKResult) -> Bool) -> ORKResult? {
guard let results = self.results as? [ORKStepResult] else { return nil }
for stepResult in results {
guard let stepResults = stepResult.results else { continue }
for result in stepResults {
if evaluate(stepResult, result) {
return result
}
}
}
return nil
}
}
|
bsd-3-clause
|
3598fa1e05495de66621bbf54ddc1fc0
| 43.82632 | 269 | 0.644142 | 5.253587 | false | false | false | false |
pjanoti/SidePanelMenu
|
Classes/SideMenuView.swift
|
1
|
14079
|
//
// SideMenuView.swift
// SideMenu
//
// Created by prema janoti on 12/26/16.
// Copyright © 2016 prema janoti. All rights reserved.
//
import UIKit
/** Enum representing different Side Panel direction*/
public enum Direction: Int {
/** Enum representing Left direction.*/
case left = 1
/** Enum representing Right direction.*/
case right = 2
}
open class Item: NSObject {
open var title: String
open var iconName: String
open var isSelected: Bool
public init(title: String, iconName: String, isSelected: Bool) {
self.title = title
self.iconName = iconName
self.isSelected = isSelected
}
}
class SideMenuTVCell: UITableViewCell {
@IBOutlet weak var iconIView: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
var item: Item?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
var imageName = self.item?.iconName
if highlighted {
self.lblTitle.textColor = UIColor.white
if imageName != nil {
imageName = imageName! + "_pressed.png"
}
self.backgroundColor = UIColor.lightGray
} else {
self.lblTitle.textColor = UIColor.black
if imageName != nil {
imageName = imageName! + "_normal.png"
}
self.backgroundColor = UIColor.white
}
if imageName != nil {
self.iconIView.image = UIImage(named: imageName!)
}
}
func updateUI(_ item: Item) {
self.item = item
self.lblTitle.text = item.title
}
}
/** Protocol for side panel. */
public protocol SideMenuViewDelegate {
/** called on side Panel delegate whenever an item is selected from side Panel.
@param selectedItem reference which is currently selected.
*/
func didSelectItem(_ item: Item)
}
/**
Custom Side Panel Menu.
*/
open class SideMenuView: UIView {
let kDefaultTransparentViewMargin = 75.0
@IBOutlet weak open var userIView: UIImageView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak open var lblUserName: UILabel!
@IBOutlet weak open var menuTView: UITableView!
@IBOutlet weak open var userInfoView: UIView!
/** Array containg Side Panel items. */
var items: [Item]?
var menuDirection: Direction?
/** Delegate to recive events from side panel */
var delegate: SideMenuViewDelegate?
open var userImageUrl: URL?
open var userName: String?
open var arrConstraints: [NSLayoutConstraint]?
/** Float value containing transparent margin of container view. */
open var transparentViewMargin: Float?
/** Background color for side panel. */
open var backGroundColor: UIColor?
/** Seperator color of tableview in side panel. */
open var separatorColor: UIColor?
/** Seperator type of tableview in side panel. */
open var separatorType: UITableViewCellSeparatorStyle?
/** side panel backGround imageview.*/
open var backGroundImageView: UIImageView?
var darkView: UIView?
var mainView: UIView?
var contView: UIView?
var isSliderVisible: Bool?
var leadingConst: NSLayoutConstraint?
var trailingConst: NSLayoutConstraint?
override open func awakeFromNib() {
super.awakeFromNib()
self.containerView.backgroundColor = UIColor.clear
let bun = Bundle(for: self.classForCoder)
self.menuTView.register(UINib.init(nibName: "SideMenuTVCell", bundle:bun ), forCellReuseIdentifier: "SideMenuTVCell")
self.menuTView.separatorInset = .zero
self.userIView.layoutIfNeeded()
self.userIView.layer.borderWidth = 3.0
self.userIView.layer.borderColor = UIColor.white.cgColor
let radius = self.userIView.frame.size.width / 2
self.userIView.layer.cornerRadius = radius
}
func setupViews() {
if self.backGroundImageView == nil {
self.backGroundImageView = UIImageView.init(frame: self.bounds)
self.backGroundImageView?.backgroundColor = UIColor.clear
self.backGroundImageView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.addSubview(self.backGroundImageView!)
self.sendSubview(toBack: self.backGroundImageView!)
}
self.menuTView.tableFooterView = UIView()
self.menuTView.backgroundColor = UIColor.clear
}
/** Initializes and returns a newly allocated side panel object with the specified delegate, and contents. Content is used as datasource for the side panel tableView
- parameter contents : Array of contents for datasource.
- parameter slideDirection : direction of side panel. (if No direction then, default direction will be Right).
- parameter delegate : delegate for the side panel.
*/
open class func initMenuView(_ contents: [Item], slideDirection: Direction?, delegate: SideMenuViewDelegate ) -> SideMenuView{
let bun = Bundle(for: self.classForCoder())
let sideView = bun.loadNibNamed("SideMenuView", owner: self, options: nil)?.last as? SideMenuView
if sideView != nil {
if slideDirection != nil {
sideView?.menuDirection = slideDirection
} else {
sideView?.menuDirection = .right
}
sideView?.items = contents
sideView?.delegate = delegate
sideView?.setupViews()
}
return sideView!
}
/** Use this method to Add initial sidepanel over a view.
- parameter view : UIView over which side panel is required.
- parameter containerView : optional UIView over which side panel is required.
*/
open func setupInitialConstraintWRTView(_ view: UIView, containerView: UIView?) {
self.mainView = view;
if containerView != nil {
self.contView = containerView;
} else {
self.contView = view
}
self.translatesAutoresizingMaskIntoConstraints = false
var topConst: NSLayoutConstraint?
var bottomConst: NSLayoutConstraint?
topConst = NSLayoutConstraint.init(item: self, attribute: .top, relatedBy: .equal, toItem: self.mainView, attribute: .top, multiplier: 1.0, constant: 64.0)
bottomConst = NSLayoutConstraint.init(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.mainView, attribute: .bottom, multiplier: 1.0, constant: 0.0)
if self.menuDirection == .right {
leadingConst = NSLayoutConstraint.init(item: self, attribute: .leading, relatedBy: .equal, toItem: self.contView, attribute: .trailing, multiplier: 1.0, constant: 0.0)
trailingConst = NSLayoutConstraint.init(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.contView, attribute: .trailing, multiplier: 1.0, constant: self.calculateSliderWidth())
} else {
leadingConst = NSLayoutConstraint.init(item: self, attribute: .leading, relatedBy: .equal, toItem: self.contView, attribute: .leading, multiplier: 1.0, constant: -(self.calculateSliderWidth()))
trailingConst = NSLayoutConstraint.init(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.contView, attribute: .leading, multiplier: 1.0, constant: 0.0)
}
view.addConstraints([topConst!, bottomConst!, leadingConst!, trailingConst!])
}
/** Using this method to calculate Slider Width on the basis of given transparent View Margin .
*/
private func calculateSliderWidth() -> CGFloat {
let screenScale = UIScreen.main.scale
var panelWidth = (UIScreen.main.currentMode?.size.width)! / screenScale
if self.transparentViewMargin != nil {
panelWidth = CGFloat(panelWidth) - CGFloat(self.transparentViewMargin!)
} else {
panelWidth = CGFloat(panelWidth) - CGFloat(kDefaultTransparentViewMargin)
}
return panelWidth
}
/** Using this method to Add Dark View over a sidepanel.
*/
private func addDarkView() {
if self.darkView == nil {
let darkView = UIView()
self.darkView = darkView
darkView.translatesAutoresizingMaskIntoConstraints = false
darkView.backgroundColor = UIColor.black
darkView.alpha = 0.0
UIView.animate(withDuration: 0.3, animations: {
darkView.alpha = 0.5
}, completion: nil)
self.mainView?.addSubview(darkView)
self.mainView?.insertSubview(self.darkView!, belowSubview: self)
let bottomSpace = NSLayoutConstraint.init(item: darkView, attribute: .bottom, relatedBy: .equal, toItem: self.mainView, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let topSpace = NSLayoutConstraint.init(item: darkView, attribute: .top, relatedBy: .equal, toItem: self.mainView, attribute: .top, multiplier: 1.0, constant: 0.0)
let leadingSpace = NSLayoutConstraint.init(item: darkView, attribute: .leading, relatedBy: .equal, toItem: self.mainView, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailingSpace = NSLayoutConstraint.init(item: darkView, attribute: .trailing, relatedBy: .equal, toItem: self.mainView, attribute: .trailing, multiplier: 1.0, constant: 0.0)
self.mainView?.addConstraints([topSpace, bottomSpace, leadingSpace, trailingSpace])
}
}
/** Using this method to remove Dark View over a sidepanel.
*/
private func removeDarkView() {
UIView.animate(withDuration: 0.3, animations: {
self.darkView!.alpha = 0.0
self.darkView?.removeFromSuperview()
self.darkView = nil
}, completion: {(finished) -> Void in
})
}
/** Use this method to Show side panel over a view without slide effect on supper view. */
open func showSidePanelWithoutSlideEffectOnSuperView() {
if self.isSliderVisible == true {
self.removeSidePanelWithoutSlideEffectOnSuperView()
return
}
self.isHidden = false
self.mainView?.endEditing(true)
self.mainView?.layoutIfNeeded()
self.mainView?.bringSubview(toFront: self)
self.addDarkView()
self.mainView?.layoutIfNeeded()
let popupWidth = self.calculateSliderWidth()
UIView.animate(withDuration: 0.3, animations: {
if popupWidth > 0 {
self.layoutIfNeeded()
if self.menuDirection == .right {
self.leadingConst?.constant = -popupWidth
self.trailingConst?.constant = 0
} else {
self.leadingConst?.constant = 0
self.trailingConst?.constant = popupWidth
}
self.mainView?.layoutIfNeeded()
}
}, completion: {(finished) -> Void in
self.mainView?.endEditing(false)
self.isSliderVisible = true
})
}
/** Use this method to Remove side panel from a view without slide efect on supper view. */
open func removeSidePanelWithoutSlideEffectOnSuperView() {
if self.isSliderVisible == false {
return
}
let popupWidth = self.calculateSliderWidth()
self.mainView?.endEditing(true)
self.mainView?.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: {
if popupWidth > 0 {
if self.menuDirection == .left {
self.leadingConst?.constant = -popupWidth
self.trailingConst?.constant = 0
} else {
self.leadingConst?.constant = 0
self.trailingConst?.constant = popupWidth
}
self.mainView?.layoutIfNeeded()
}
}, completion: {(finished) -> Void in
self.isHidden = false
self.mainView?.endEditing(false)
self.isSliderVisible = false
self.mainView?.sendSubview(toBack: self)
if self.darkView != nil {
self.removeDarkView()
}
})
}
}
extension SideMenuView: UITableViewDelegate, UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count = 0
if (self.items?.count)! > 0 {
count = (self.items?.count)!
}
return count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuTVCell", for: indexPath) as? SideMenuTVCell
cell?.selectionStyle = .none
if (self.items?.count)! > 0 {
let item = self.items?[indexPath.row]
cell?.updateUI(item!)
}
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.resetAllSliderItemsSelectedState()
tableView.deselectRow(at: indexPath, animated: true)
let currentSelectedItem = self.items?[indexPath.row]
currentSelectedItem?.isSelected = true
if self.delegate != nil {
self.delegate?.didSelectItem(currentSelectedItem!)
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
func resetAllSliderItemsSelectedState() {
for item in self.items! {
item.isSelected = false
}
}
}
|
apache-2.0
|
2fdc9a966776e7604ca151547c20797f
| 36.145119 | 205 | 0.628711 | 4.881415 | false | false | false | false |
ZackKingS/Tasks
|
task/Classes/Me/Controller/ZBSetingController.swift
|
1
|
6117
|
//
// ZBSetingController.swift
// task
//
// Created by 柏超曾 on 2017/9/26.
// Copyright © 2017年 柏超曾. All rights reserved.
//
import Foundation
import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON
class ZBSetingController: UITableViewController ,UIAlertViewDelegate{
@IBOutlet weak var sizeBtn: UIButton!
@IBOutlet weak var logoutBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupConfig()
let s = " \(ZBCleanTool.fileSizeOfCache()) M"
sizeBtn.setTitle(s, for: .normal)
}
@IBAction func clear(_ sender: Any) {
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 50
}else if indexPath.row == 1{
return 50
}else if indexPath.row == 2{
return 50
}else if indexPath.row == 3{
return screenHeight - 50 * 2 - 20
}
return 60
}
@IBAction func logout(_ sender: Any) {
UserDefaults.standard.set(false, forKey: ZBLOGIN_KEY)
UserDefaults.standard.synchronize()
navigationController?.popViewController(animated: true)
}
func setupConfig(){
tableView.backgroundColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont.systemFont(ofSize: 18)
] //UIFont(name: "Heiti SC", size: 24.0)!
navigationItem.title = "设置";
tableView.contentInset = UIEdgeInsets.init(top: -20, left: 0, bottom: 0, right: 0);
self.tableView.sectionFooterHeight = 0;
self.tableView.sectionHeaderHeight = screenHeight / 3;
logoutBtn.layer.cornerRadius = kScornerRadius
logoutBtn.layer.masksToBounds = true
ZBCleanTool.fileSizeOfCachingg(completionHandler: { (size) in
self.sizeBtn.setTitle((size ), for: .normal)
})
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
alcer()
}else if indexPath.row == 1{
navigationController?.pushViewController(ZBAboutMe(), animated: true)
}else if indexPath.row == 2{
checkupdate()
}
tableView.deselectRow(at: indexPath, animated: true)
}
func alcer(){
let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
// change the style sheet text color
alert.view.tintColor = UIColor.black
let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
let actionCamera = UIAlertAction.init(title: "确定", style: .default) { (UIAlertAction) -> Void in
self.cleannn()
}
alert.addAction(actionCancel)
alert.addAction(actionCamera)
self.present(alert, animated: true, completion: nil)
}
private func cleannn(){
ZBCleanTool.clearCache()
SVProgressHUD.show()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
SVProgressHUD.showSuccess(withStatus: "")
SVProgressHUD.setAnimationDuration(1)
self.sizeBtn.setTitle(" 0 M", for: .normal)
}
}
func checkupdate (){
Alamofire.request(API_SOFTWARE_UPDATA_URL+"?platform=2", parameters: nil ).responseJSON { (response) in
//判断是否成功
guard response.result.isSuccess else {
return
}
if let value = response.result.value {
let infoDictionary = Bundle.main.infoDictionary
let currentAppVersion = infoDictionary!["CFBundleShortVersionString"] as! String
let json = JSON(value)
let version_name = json["data"]["version_name"].stringValue
print(currentAppVersion)
print(version_name)
if currentAppVersion != version_name {
print( "去更新")
let des = json["data"]["update_state"].stringValue
self.compareVersion(currentAppVersion, storeVersion: version_name, note: des)
}else{
self.showHint(hint: "已经是最新版本")
}
}
}
}
fileprivate func compareVersion(_ localVersion: String, storeVersion: String,note:String) {
let message = "本次更新内容:\n\(note)"
if localVersion.compare(storeVersion) == ComparisonResult.orderedAscending {
let alertView = UIAlertView(title: "发现新版本",message: message,delegate: self as? UIAlertViewDelegate,cancelButtonTitle: nil,otherButtonTitles: "马上更新","下次再说")
alertView.delegate = self
alertView.tag = 10086
alertView.show()
}
}
func alertView(_ alertView:UIAlertView, clickedButtonAt buttonIndex: Int){
if(alertView.tag == 10086) {
if(buttonIndex == 0){
UIApplication.shared.openURL(URL(string:"https://itunes.apple.com/cn/app/wei-xin/id414478124?mt=8")!)
}else{
//下次再说
}
}
}
}
|
apache-2.0
|
409ecc31de6b501852c4e1bb347243c9
| 25.950673 | 167 | 0.527454 | 5.323295 | false | false | false | false |
thefuntasty/TFTransparentNavigationBar
|
Pod/Classes/CGRect+Tools.swift
|
1
|
738
|
//
// CGRect+Tools.swift
// TFTransparentNavigationBar
//
// Created by Ales Kocur on 10/03/2015.
// Copyright (c) 2015 Ales Kocur. All rights reserved.
//
import UIKit
enum Direction {
case Top, Bottom, Left, Right
}
extension CGRect {
func additiveRect(value: CGFloat, direction: Direction) -> CGRect {
var rect = self
switch direction {
case .Top:
rect.origin.y -= value
rect.size.height += value
case .Bottom:
rect.size.height += value
case .Left:
rect.origin.x -= value
rect.size.width += value
case .Right:
rect.size.width += value
}
return rect
}
}
|
mit
|
81ebf1cd3676f99e3be506bcde2dd5ab
| 20.085714 | 71 | 0.54065 | 4.01087 | false | false | false | false |
grimbolt/BaseSwiftProject
|
BaseSwiftProject/Sources/Types/InfoOverlay.swift
|
1
|
1971
|
import Foundation
import UIKit
import SnapKit
public class InfoOverlay {
public private(set) static var instance = InfoOverlay()
private var window: UIWindow!
private var view: UIView!
private var label: UILabel!
private init() {
DispatchQueue.main.async {
self.createWindow()
self.createView()
}
}
public static var visible: Bool = false {
didSet {
self.instance.visible = visible
}
}
public var visible: Bool = false {
didSet {
self.view?.isHidden = !visible
}
}
public static var additionalText: String = "" {
didSet {
self.instance.label.text = self.instance.stringForLabel()
}
}
private func stringForLabel() -> String {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"
let debug: String
#if DEBUG
debug = "D"
#else
debug = ""
#endif
return InfoOverlay.additionalText+" "+version+debug
}
private func createWindow() {
let window = UIWindow()
self.window = window
window.windowLevel = UIWindowLevelAlert+1
window.isHidden = false
window.backgroundColor = .clear
window.isUserInteractionEnabled = false
}
private func createView() {
self.view = UIView()
view.isHidden = !self.visible
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
self.label = UILabel()
label.text = self.stringForLabel()
label.font = label.font.withSize(5)
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
self.window.addSubview(view)
view.snp.makeConstraints {
make in
make.leading.top.equalTo(0)
make.edges.equalTo(label)
}
}
}
|
mit
|
ebcfaa5db1dc5dc6f78f6543eba3e18b
| 24.269231 | 97 | 0.589548 | 4.977273 | false | false | false | false |
Nyx0uf/MPDRemote
|
src/common/extensions/UIColor+Extensions.swift
|
1
|
4041
|
// UIColor+Extensions.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension UIColor
{
// MARK: - Initializers
public convenience init(rgb: Int32, alpha: CGFloat)
{
let red = ((CGFloat)((rgb & 0xFF0000) >> 16)) / 255
let green = ((CGFloat)((rgb & 0x00FF00) >> 8)) / 255
let blue = ((CGFloat)(rgb & 0x0000FF)) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public convenience init(rgb: Int32)
{
self.init(rgb: rgb, alpha: 1.0)
}
func inverted() -> UIColor
{
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
getRed(&r, green: &g, blue: &b, alpha: &a)
return UIColor(red: 1.0 - r, green: 1.0 - g, blue: 1.0 - b, alpha: 1.0)
}
func isBlackOrWhite() -> Bool
{
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
getRed(&r, green: &g, blue: &b, alpha: &a)
if (r > 0.91 && g > 0.91 && b > 0.91)
{
return true // white
}
if (r < 0.09 && g < 0.09 && b < 0.09)
{
return true // black
}
return false
}
func isDark() -> Bool
{
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
getRed(&r, green: &g, blue: &b, alpha: &a)
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
if (lum < 0.5)
{
return true
}
return false
}
func colorWithMinimumSaturation(_ minSaturation: CGFloat) -> UIColor
{
var h: CGFloat = 0.0, s: CGFloat = 0.0, v: CGFloat = 0.0, a: CGFloat = 0.0
getHue(&h, saturation: &s, brightness: &v, alpha: &a)
if (s < minSaturation)
{
return UIColor(hue: h, saturation: s, brightness: v, alpha: a)
}
return self
}
func isDistinct(fromColor compareColor: UIColor) -> Bool
{
var r1: CGFloat = 0.0, g1: CGFloat = 0.0, b1: CGFloat = 0.0, a1: CGFloat = 0.0
var r2: CGFloat = 0.0, g2: CGFloat = 0.0, b2: CGFloat = 0.0, a2: CGFloat = 0.0
self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
compareColor.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
let threshold: CGFloat = 0.25
if (fabs(r1 - r2) > threshold || fabs(g1 - g2) > threshold || fabs(b1 - b2) > threshold || fabs(a1 - a2) > threshold)
{
// check for grays, prevent multiple gray colors
if (fabs(r1 - g1) < 0.03 && fabs(r1 - b1) < 0.03)
{
if (fabs(r2 - g2) < 0.03 && fabs(r2 - b2) < 0.03)
{
return false
}
}
return true
}
return false
}
func isContrasted(fromColor color: UIColor) -> Bool
{
var r1: CGFloat = 0.0, g1: CGFloat = 0.0, b1: CGFloat = 0.0, a1: CGFloat = 0.0
var r2: CGFloat = 0.0, g2: CGFloat = 0.0, b2: CGFloat = 0.0, a2: CGFloat = 0.0
getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
color.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
let lum1 = 0.2126 * r1 + 0.7152 * g1 + 0.0722 * b1
let lum2 = 0.2126 * r2 + 0.7152 * g2 + 0.0722 * b2
var contrast: CGFloat = 0.0
if (lum1 > lum2)
{
contrast = (lum1 + 0.05) / (lum2 + 0.05)
}
else
{
contrast = (lum2 + 0.05) / (lum1 + 0.05)
}
return contrast > 1.6
}
}
|
mit
|
16af060d9b7e37ed63127ed53aa12fa2
| 27.659574 | 119 | 0.62435 | 2.7341 | false | false | false | false |
solon1/learniOSDemo
|
Swift/firstSwift.playground/Contents.swift
|
1
|
3848
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print("hello,world")
//let声明常量 var声明变量
let year:CGFloat = 98
var sum: NSInteger = 888
let letCount : CGFloat = 999.0
//字符串+数字
let sumi = "hello"
let width : NSInteger = 90
let sumWidth = sumi + String(width)
//定义2个常量 用\转换数字为字符串
let num1 = 4
let num2 = 5
let appleSum = "I have \(num1) apple"
let fruitSum = "I have \(num1 + num2) fruit"
let floatS = 2.555
let floatSum = "I have solon \(floatS)"
//数组和字典的使用
var shoppingList = ["catfish","water","tulips","bluePaint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm" : "Captain",
"Kaylee" : "Mechanic",
]
occupations["jayne"] = "Public Relation"
//创建一个空数组或者是字典
let emptyArray = [String]()
let emptyDictionary = [String : Float]()
let individualScores = [75,43,103,87,12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//可选值,因为swift特殊语法如 if score 这样的条件表达式
//score不会隐式与0作对比,所以会报错,如下所示
//if emptyArray {
//
//}
var optionalString: String? = "hello"
print(optionalString == nil)
var optionalName: String? = "solon"
var greeting = "Hello!"
if let name = optionalName {
greeting = "hello,\(name)"
}
//switch case
let vagetable = "red pepper"
switch vagetable {
case "celery" :print("Add some raisins")
case "cucumber","watercress" :print("That would make a")
case let x where x.hasSuffix("pepper") : print("Is it a spicy \(x)?")
default:print("everything tastes")
}
//使用forin便利字典求最大数
var interestingNumbers = [
"prime" : [2,3,5,7,11],
"Fibonacci":[1,1,2,3],
"Square":[1,4,9,16,25],
]
var largest = 0
for (kind,numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
//使用while 也可以把条件放在结尾
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
//使用..<表示范围
var firstForLoop = 0
for i in 0 ..< 4 {
firstForLoop += i
}
print(firstForLoop)
var secondForLoop = 0
for var i = 0;i < 4;++i {
secondForLoop += i
}
print(secondForLoop)
//函数和闭包 使用->表示返回值类型
func greet(name:String, day: String) ->String {
return "Hello \(name),today is \(day)"
}
greet("Bob", day: "Tuesday")
//使用元组让数组返回多个参数
func calculateStatistics(scores :[Int])->(min: Int,max: Int,sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
}else if score < min {
min = score
}
sum += score
}
return (min,max,sum)
}
let statistics = calculateStatistics([2,3,5,34,23,33,99])
print(statistics.sum)
print(statistics.2)
//函数可以带有可变个数的参数
func sumOf(numbers: Int...) ->Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42,777,34)
//函数可以嵌套,被嵌套的函数可以访问外侧函数的变量
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen();
//函数可以作为另一个函数的返回值
func makeIncrementer() -> (Int -> Int) {
func addOne(number:Int) ->Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
//函数也可以当做参数传入另一个函数
func hasAnyMatches(list:[Int],contition:Int -> Bool) ->Bool {
}
|
mit
|
6586aa5e34b6d80d01671a1b6882fac9
| 15.28436 | 71 | 0.616414 | 2.998255 | false | false | false | false |
BananosTeam/CreativeLab
|
Assistant/AppDelegate.swift
|
1
|
1909
|
//
// AppDelegate.swift
// Assistant
//
// Created by Bananos on 5/14/16.
// Copyright © 2016 Bananos. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var sharedDelegate: AppDelegate? {
return UIApplication.sharedApplication().delegate as? AppDelegate
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
TrelloDataHandler.shared.loadData()
if let _ = Trello.shared.getToken() {
let trelloRequester = TrelloRequester()
trelloRequester.getCardsForMemberId("5736fea69bc9bb59fdee87a3") {
print($0)
}
}
if SlackClient.Token == nil {
SlackClient.Authenticate()
} else {
SlackClient.currentClient = SlackClient()
SlackClient.currentClient?.start()
window?.rootViewController = NavigationController.instantiateFromStoryboard()
}
return true
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
guard let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false),
queries = components.queryItems else { return false }
if !(queries.filter { $0.name == "code" }).isEmpty {
SlackClient.ContinueAuthentication(url) { isAuthenticated in
guard isAuthenticated else { return }
SlackClient.currentClient = SlackClient()
SlackClient.currentClient?.start()
self.window?.rootViewController = NavigationController.instantiateFromStoryboard()
}
return true
} else {
Trello.shared.handleCallbackUrlWithQueryItems(queries)
return true
}
}
}
|
mit
|
ee649e2fa89a3f02a25cef2d6f04279b
| 33.071429 | 127 | 0.6326 | 5.256198 | false | false | false | false |
hemantasapkota/OpenSansSwift
|
example/OpenSansSwiftExample/OpenSansSwiftExample/ViewController.swift
|
1
|
2906
|
//
// ViewController.swift
// OpenSansSwiftExample
//
// Created by Hemanta Sapkota on 21/02/2015.
// Copyright (c) 2015 Open Learning Pty Ltd. All rights reserved.
//
import UIKit
import OpenSansSwift
class ViewController: UIViewController {
let size = CGSize(width: 400, height: 50)
func makeFontLabel(x:CGFloat, y:CGFloat, font:UIFont) -> UILabel {
let lbl1 = UILabel(frame: CGRectMake(x, y, size.width, size.height))
lbl1.font = font
lbl1.text = font.fontName
return lbl1
}
override func viewDidLoad() {
super.viewDidLoad()
//Register Open Sans fonts
OpenSans.registerFonts()
let x = UIScreen.mainScreen().bounds.width / 2
var x1 = x - size.width / 3
var y1 = CGFloat(100)
// let fontNames = [
// "OpenSans-Regular",
// "OpenSans-Bold",
// "OpenSans-BoldItalic",
// "OpenSans-ExtraBold",
// "OpenSans-ExtraBoldItalic",
// "OpenSans-Italic",
// "OpenSans-Light",
// "OpenSans-LightItalic",
// "OpenSans-Semibold",
// "OpenSans-SemiboldItalic"
// ]
let f1 = UIFont.openSansFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f1))
y1 += 50
let f2 = UIFont.openSansBoldFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f2))
y1 += 50
let f3 = UIFont.openSansBoldItalicFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f3))
y1 += 50
let f4 = UIFont.openSansExtraBoldFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f4))
y1 += 50
let f5 = UIFont.openSansExtraBoldItalicFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f5))
y1 += 50
let f6 = UIFont.openSansItalicFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f6))
y1 += 50
let f7 = UIFont.openSansLightFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f7))
y1 += 50
let f8 = UIFont.openSansLightItalicFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f8))
y1 += 50
let f9 = UIFont.openSansSemiboldFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f9))
y1 += 50
let f10 = UIFont.openSansSemiboldItalicFontOfSize(30)
self.view.addSubview(makeFontLabel(x1, y: y1, font: f10))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
9849cac9f695d16649169591ad6368fc
| 27.490196 | 76 | 0.562973 | 3.986283 | false | false | false | false |
evering7/Speak
|
iSpeaking/Utilities.swift
|
1
|
10269
|
//
// Utilities.swift
// iSpeaking
//
// Created by JianFei Li on 29/04/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import UIKit
enum LogLevel: UInt8 {
case debugConsole = 1
case outputToFile = 2
case displayOnScreen = 4
case tidyLog = 3
case fullLog = 7
}
func printLog <T> (message: T,
logLevel: LogLevel = .tidyLog,
file: String = #file,
method: String = #function,
line: Int = #line
)
{
var strShow = Date().toString()
// var strShow = "\(currentDate.hour()):\(currentDate.minute()):\(currentDate.second()) "
strShow += " \((file as NSString).lastPathComponent) [\(line)] [\(method)] \(message)"
// 1 Show in the command console
if (logLevel.rawValue & LogLevel.debugConsole.rawValue) == LogLevel.debugConsole.rawValue {
debugPrint(strShow)
}
// 2 Output to log file
if (logLevel.rawValue & LogLevel.outputToFile.rawValue) == LogLevel.outputToFile.rawValue {
let logFile = getLogFilePath()
writeToFile(content: strShow, filePath: logFile)
}
// 3 output to iphone screen
if (logLevel.rawValue & LogLevel.displayOnScreen.rawValue) == LogLevel.displayOnScreen.rawValue {
let objAlertController = UIAlertController(title: "Alert Message", message: strShow, preferredStyle: .alert)
let objAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
let objActionCopy = UIAlertAction(title: "Copy Text", style: .default, handler:{ (UIAlertAction) in
print("Done !!")
print("Item : \(strShow)")
UIPasteboard.general.string = strShow
}
)
objAlertController.addAction(objAction)
objAlertController.addAction(objActionCopy)
// viewController.present(objAlertController, animated: true, completion: nil)
// UIApplication.shared.keyWindow?.rootViewController?.present(objAlertController, animated: true, completion: nil)
let topVC = UIApplication.topViewController()
topVC?.present(objAlertController, animated: true, completion: nil)
// window?.rootViewController?.present(objAlertController, animated: true, completion: nil)
// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 4
DispatchQueue.main.asyncAfter(deadline: when){
// your code with delay
objAlertController.dismiss(animated: true, completion: nil)
}
}
}
func getLogFilePath() -> String {
let filePath = NSHomeDirectory() + "/Documents/JFLogFile.log"
// let folderPath = NSHomeDirectory() + "/Documents/log/"
//
// if !isExistDirectory(folderPath: folderPath){
// makeFolder(folderPath: folderPath)
// }
// error output You don’t have permission to save the file “log” in the folder “Documents”
return filePath
}
func makeFolder(folderPath: String){
// let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
// let documentsDirectory: AnyObject = paths[0] as AnyObject
// let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
let dataPath = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
}
func isExistDirectory(folderPath: String) -> Bool {
let fileManager = FileManager.default
var isDir : ObjCBool = false
if fileManager.fileExists(atPath: folderPath, isDirectory:&isDir) {
if isDir.boolValue {
// file exists and is a directory
return true
} else {
// file exists and is not a directory
print("It is a file, not a folder: \(folderPath)")
return false
}
} else {
// file does not exist
return false
}
}
func isFileExistForFullPath(fileFullPath: String) -> Bool {
let fileManager = FileManager.default
var isDir : ObjCBool = false
if fileManager.fileExists(atPath: fileFullPath, isDirectory: &isDir) {
if isDir.boolValue {
// exist a folder
return false
}else {
printLog(message: "FILE AVAILABLE \(fileFullPath)")
return true
}
} else {
printLog(message: "FILE NOT AVAILABLE \(fileFullPath)")
return false
}
}
func writeToFile(content: String, filePath: String) {
let contentToAppend = content+"\n"
//Check if file exists
if let fileHandle = FileHandle(forWritingAtPath: filePath) {
//Append to file
fileHandle.seekToEndOfFile()
fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!)
}
else {
//Create new file
do {
try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Error creating \(filePath)")
}
}
}
func isFileExist(fileFullPath: String) -> Bool {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: fileFullPath) {
printLog(message: "FILE AVAILABLE \(fileFullPath)")
return true
} else {
printLog(message: "FILE NOT AVAILABLE \(fileFullPath)")
return false
}
}
func getText(fileURL: URL, encoding: String.Encoding) -> String? {
if !isFileExist(fileFullPath: fileURL.path) {
printLog(message: "File not exist, can't get text. \(fileURL.path)")
return nil
}
do {
let text = try String(contentsOf: fileURL, encoding: encoding)
return text
}catch let error {
printLog(message: "\(error.localizedDescription)")
return nil
}
}
func getDefaultTime() -> Date {
return Date(timeIntervalSince1970: 50)
}
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
return dateFormatter.string(from: self)
}
func toLocalTime(dateFormat: String) -> String {
// let dateFormatter = DateFormatter()
// dateFormatter.setda
let formatter:DateFormatter = DateFormatter()
formatter.dateFormat = dateFormat
formatter.timeZone = TimeZone.ReferenceType.system
let str = formatter.string(from: self)
return str
}
}
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
func getUnusedRandomFeedXmlFileURL() -> URL {
// 1. get document dir
let documentDirURL = FileManager.documentsDirURL().appendingPathComponent("RSSXMLDownFolder")
// 2. get random string
var randomFileName = String.random() + ".xml"
var randomFileURL = documentDirURL.appendingPathComponent(randomFileName)
// 3. check existence by loop
while isFileExist(fileFullPath: randomFileURL.path){
randomFileName = String.random() + ".xml"
randomFileURL = documentDirURL.appendingPathComponent(randomFileName)
}
return randomFileURL
}
func getRSSxmlFileURLfromLastComponent(lastPathCompo: String) -> URL {
let documentDirURL = FileManager.documentsDirURL().appendingPathComponent("RSSXMLDownFolder")
let fileURL = documentDirURL.appendingPathComponent(lastPathCompo)
printLog(message: "new fileURL: \(fileURL.path)")
return fileURL
}
func getRSSXMLDownloadHomeFolderURL() -> URL? {
let documentDirURL = FileManager.documentsDirURL().appendingPathComponent("RSSXMLDownFolder")
printLog(message: "\(documentDirURL.path)")
if isExistDirectory(folderPath: documentDirURL.path){
return documentDirURL
}
do {
try FileManager.default.createDirectory(at: documentDirURL, withIntermediateDirectories: true, attributes: nil)
return documentDirURL
}catch let error as NSError {
printLog(message: "unable to create directory \(error.debugDescription)")
return nil
}
}
extension FileManager {
class func documentsDirPath() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
return paths[0]
}
class func documentsDirURL() -> URL {
// var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
return URL(fileURLWithPath: documentsDirPath(), isDirectory: true)
}
class func cachesDirPath() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
return paths[0]
}
}
extension String {
static func random(length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString : String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
}
|
mit
|
5fb1f6046629dad949cea99150e04183
| 28.142045 | 159 | 0.647397 | 4.953163 | false | false | false | false |
wj2061/ios7ptl-swift3.0
|
ch19-UIDynamics/TearOff/TearOff/DraggableView.swift
|
1
|
1792
|
//
// DraggableView.swift
// TearOff
//
// Created by wj on 15/11/19.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class DraggableView: UIView,NSCopying {
var dynamicAnimator:UIDynamicAnimator
var gestureRecognizer:UIPanGestureRecognizer!
var snapBehavior:UISnapBehavior?
init(frame:CGRect,animator:UIDynamicAnimator){
dynamicAnimator = animator
super.init(frame: frame)
backgroundColor = UIColor.darkGray
layer.borderWidth = 2
gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(DraggableView.handlePan(_:)))
self.addGestureRecognizer(gestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handlePan(_ gesture: UIPanGestureRecognizer){
switch gesture.state{
case .cancelled, .ended:
stopDragging()
default:
let point = gesture.location(in: superview!)
dragToPoint(point)
}
}
func copy(with zone: NSZone?) -> Any {
let newView = DraggableView(frame: CGRect.zero, animator: dynamicAnimator)
newView.bounds = bounds
newView.center = center
newView.transform = transform
newView.alpha = alpha
return newView
}
func dragToPoint(_ point:CGPoint){
if let behavior = snapBehavior{
dynamicAnimator.removeBehavior(behavior)
}
snapBehavior = UISnapBehavior(item: self, snapTo: point)
snapBehavior?.damping = 0.25
dynamicAnimator.addBehavior(snapBehavior!)
}
func stopDragging(){
dynamicAnimator.removeBehavior(snapBehavior!)
snapBehavior = nil
}
}
|
mit
|
5c5a09873091f26ba46260719d6b6328
| 26.953125 | 112 | 0.640581 | 5.096866 | false | false | false | false |
vgatto/protobuf-swift
|
src/ProtocolBuffers/ProtocolBuffersTests/MapFieldsTests.swift
|
2
|
1243
|
//
// MapFieldsTests.swift
// ProtocolBuffers
//
// Created by Alexey Khokhlov on 20.05.15.
// Copyright (c) 2015 alexeyxo. All rights reserved.
//
import XCTest
import Foundation
import ProtocolBuffers
class MapFieldsTests: XCTestCase {
func testMapsFields()
{
var mes1Builder = SwiftProtobufUnittest.MessageContainsMap.Builder()
mes1Builder.mapInt32Int32 = [1:2]
mes1Builder.mapInt64Int64 = [3:4]
mes1Builder.mapStringString = ["a":"b"]
mes1Builder.mapStringBytes = ["d":CodedInputStreamTests().bytesArray([1,2,3,4])]
var containingMessage = SwiftProtobufUnittest.MapMessageValue.Builder().setValueInMapMessage(32).build()
mes1Builder.mapStringMessage = ["c":containingMessage]
var mes1 = mes1Builder.build()
var mes2 = SwiftProtobufUnittest.MessageContainsMap.Builder().mergeFrom(mes1).build()
XCTAssert(mes1 == mes2, "")
XCTAssert(mes2.mapInt32Int32 == [1:2], "")
XCTAssert(mes2.mapInt64Int64 == [3:4], "")
XCTAssert(mes2.mapStringString == ["a":"b"], "")
XCTAssert(mes2.mapStringMessage == ["c":containingMessage], "")
XCTAssert(mes2.mapStringMessage["c"]?.valueInMapMessage == 32, "")
}
}
|
apache-2.0
|
a7fe2d29a705258e44c45adc56316468
| 35.558824 | 112 | 0.666935 | 3.884375 | false | true | false | false |
zzyrd/ChicagoFoodInspection
|
ChicagoFoodApp/ChicagoFoodApp/Inspection+CoreDataClass.swift
|
1
|
698
|
//
// Inspection+CoreDataClass.swift
// ChicagoFoodApp
//
// Created by zhang zhihao on 4/22/17.
// Copyright © 2017 YUNFEI YANG. All rights reserved.
//
import Foundation
import CoreData
@objc(Inspection)
public class Inspection: NSManagedObject {
convenience init?(type: String, result: String, violation: String, id: Int, date: Date) {
guard let context = Model.sharedInstance.managedContext else { return nil }
self.init(entity: Inspection.entity(), insertInto: context)
self.type = type
self.results = result
self.violation = violation
self.id = Int32(id)
self.date = date as NSDate
}
}
|
mit
|
8863401e22c52c8830cdaa7e98caf56c
| 23.034483 | 93 | 0.639885 | 4.052326 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Controllers/Chat/MessagesSizingManager.swift
|
1
|
1446
|
//
// MessagesSizingViewModel.swift
// Rocket.Chat
//
// Created by Rafael Streit on 25/09/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
final class MessagesSizingManager {
internal var cache: [AnyHashable: NSValue] = [:]
internal var nibsCache: [AnyHashable: Any] = [:]
/**
Clear all height values cached.
*/
func clearCache() {
cache = [:]
nibsCache = [:]
}
func invalidateLayout(for identifier: AnyHashable) {
cache.removeValue(forKey: identifier)
}
/**
Returns the cached size for the IndexPath.
*/
func size(for identifier: AnyHashable) -> CGSize? {
guard
let size = cache[identifier]?.cgSizeValue,
!size.width.isNaN && size.width >= 0,
!size.height.isNaN && size.height >= 0
else {
return nil
}
return size
}
/**
Sets the cached size for the identified cell.
*/
func set(size: CGSize, for identifier: AnyHashable) {
return cache[identifier] = NSValue(cgSize: size)
}
/**
Returns the cached view for identifier.
*/
func view(for identifier: AnyHashable) -> Any? {
return nibsCache[identifier]
}
/**
Sets the cached view to specific identifier.
*/
func set(view: Any, for identifier: AnyHashable) {
return nibsCache[identifier] = view
}
}
|
mit
|
9a685539fc3a413a9af430cbd4e241fb
| 21.578125 | 57 | 0.587543 | 4.35241 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
Classes/MagicSearch.swift
|
1
|
4492
|
//
// ContactListMagicSearch.swift
// linphone
//
// Created by QuentinArguillere on 25/03/2022.
//
import Foundation
import linphonesw
@objc class MagicSearchSingleton : NSObject {
static var theMagicSearchSingleton: MagicSearchSingleton?
var lc = CallManager.instance().lc
var ongoingSearch = false
var needUpdateLastSearchContacts = false
var lastSearchContacts : [Contact] = []
@objc var currentFilter : String = ""
var previousFilter : String?
var magicSearch : MagicSearch
var magicSearchDelegate : MagicSearchDelegate?
override init() {
magicSearch = try! lc!.createMagicSearch()
magicSearch.limitedSearch = false
super.init()
magicSearchDelegate = MagicSearchDelegateStub(onSearchResultsReceived: { (magicSearch: MagicSearch) in
self.needUpdateLastSearchContacts = true
self.ongoingSearch = false
Log.directLog(BCTBX_LOG_MESSAGE, text: "Contact magic search -- filter = \(String(describing: self.previousFilter)) -- \(magicSearch.lastSearch.count) contact founds")
NotificationCenter.default.post(name: Notification.Name(kLinphoneMagicSearchFinished), object: self)
}, onLdapHaveMoreResults: { (magicSearch: MagicSearch, ldap: Ldap) in
Log.directLog(BCTBX_LOG_MESSAGE, text: "Ldap have more result")
})
magicSearch.addDelegate(delegate: magicSearchDelegate!)
}
@objc static func instance() -> MagicSearchSingleton {
if (theMagicSearchSingleton == nil) {
theMagicSearchSingleton = MagicSearchSingleton()
}
return theMagicSearchSingleton!
}
func getContactFromAddr(addr: Address) -> Contact? {
return LinphoneManager.instance().fastAddressBook.addressBookMap.object(forKey: addr.asStringUriOnly() as Any) as? Contact
}
func getContactFromPhoneNb(phoneNb: String) -> Contact? {
let contactKey = FastAddressBook.localizedLabel(FastAddressBook.normalizeSipURI( lc?.defaultAccount?.normalizePhoneNumber(username: phoneNb) ?? phoneNb))
return LinphoneManager.instance().fastAddressBook.addressBookMap.object(forKey: contactKey as Any) as? Contact
}
func searchAndAddMatchingContact(searchResult: SearchResult) -> Contact? {
if let friend = searchResult.friend {
if let addr = friend.address, let foundContact = getContactFromAddr(addr: addr) {
return foundContact
}
for phoneNb in friend.phoneNumbers {
if let foundContact = getContactFromPhoneNb(phoneNb: phoneNb) {
return foundContact
}
}
// No contacts found (searchResult likely comes from LDAP), creating a new one
if let newContact = Contact(friend: friend.getCobject) {
newContact.createdFromLdap = true
return newContact
}
}
if let addr = searchResult.address, let foundContact = getContactFromAddr(addr: addr) {
return foundContact
}
if let foundContact = getContactFromPhoneNb(phoneNb: searchResult.phoneNumber) {
return foundContact
}
return nil
}
@objc func isSearchOngoing() -> Bool {
return ongoingSearch
}
@objc func getLastSearchResults() -> UnsafeMutablePointer<bctbx_list_t>? {
var cList: UnsafeMutablePointer<bctbx_list_t>? = nil
for data in magicSearch.lastSearch {
cList = bctbx_list_append(cList, UnsafeMutableRawPointer(data.getCobject))
}
return cList
}
@objc func getLastSearchContacts() -> [Contact] {
if (needUpdateLastSearchContacts) {
lastSearchContacts = []
var addedContactNames : [String] = []
for res in magicSearch.lastSearch {
if let contact = searchAndAddMatchingContact(searchResult: res) {
if (!addedContactNames.contains(contact.displayName)) {
addedContactNames.append(contact.displayName)
lastSearchContacts.append(contact)
}
}
}
needUpdateLastSearchContacts = false
}
return lastSearchContacts
}
@objc func searchForContacts(domain: String, sourceFlags: Int, clearCache: Bool) {
if (clearCache) {
magicSearch.resetSearchCache()
}
if let oldFilter = previousFilter {
if (oldFilter.count > currentFilter.count || oldFilter != currentFilter) {
magicSearch.resetSearchCache()
}
}
previousFilter = currentFilter
ongoingSearch = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
if (self.ongoingSearch) {
NotificationCenter.default.post(name: Notification.Name(kLinphoneMagicSearchStarted), object: self)
}
}
magicSearch.getContactsListAsync(filter: currentFilter, domain: domain, sourceFlags: sourceFlags, aggregation: MagicSearchAggregation.Friend)
}
func setupLDAPTestSettings() {
}
}
|
gpl-3.0
|
e888507f43148ee8c01e4255bc54c1c8
| 30.858156 | 170 | 0.743321 | 3.663948 | false | false | false | false |
philipbannon/iOS
|
ToDoListWithCoreData/ToDoListWithCoreData/ViewController.swift
|
1
|
3099
|
//
// ViewController.swift
// ToDoListWithCoreData
//
// Created by Philip Bannon on 07/01/2016.
// Copyright © 2016 Philip Bannon. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var txtField : UITextField!
var todoItems : [ItemEntity] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.dataSource = self
self.tableView.delegate = self
loadItems()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todoItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let item = self.todoItems[indexPath.row]
cell.textLabel!.text = item.title
return cell
}
func configurationTextField(textField : UITextField) {
textField.placeholder = "Enter New Item"
self.txtField = textField
}
func loadItems() {
do {
try context.save()
} catch {
print("something went wrong")
}
let request = NSFetchRequest(entityName: "ItemEntity")
var results : [AnyObject]?
do {
results = try context.executeFetchRequest(request)
} catch {
results = nil
}
if (results != nil) {
self.todoItems = results as! [ItemEntity]
}
self.tableView.reloadData()
}
func saveNewItem() {
let item = NSEntityDescription.insertNewObjectForEntityForName("ItemEntity", inManagedObjectContext: context) as! ItemEntity
item.title = txtField.text
loadItems()
}
@IBAction func addButtonPressed(sender: AnyObject) {
alertPopup()
}
func alertPopup() {
let alert = UIAlertController(title: "Add New Item", message: nil, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in alert.dismissViewControllerAnimated(true, completion: nil)
}
let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) {
UIAlertAction in self.saveNewItem()
}
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(cancelAction)
alert.addAction(saveAction)
self.presentViewController(alert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
gpl-2.0
|
93bef1838b31c52864252900005d90cf
| 27.163636 | 132 | 0.623628 | 5.454225 | false | false | false | false |
ipmobiletech/firefox-ios
|
Client/Frontend/Browser/TabTrayController.swift
|
4
|
24597
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextColor = UIColor.blackColor()
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
// UIcollectionViewController doesn't let us specify a style for recycling views. We override the default style here.
class TabCell: UICollectionViewCell {
let backgroundHolder: UIView
let background: UIImageViewAligned
let titleText: UILabel
let title: UIVisualEffectView
let innerStroke: InnerStrokedView
let favicon: UIImageView
let closeButton: UIButton
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder = UIView()
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background = UIImageViewAligned()
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon = UIImageView()
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.title = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
self.title.layer.shadowColor = UIColor.blackColor().CGColor
self.title.layer.shadowOpacity = 0.2
self.title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
self.title.layer.shadowRadius = 0
self.titleText = UILabel()
self.titleText.textColor = TabTrayControllerUX.TabTitleTextColor
self.titleText.backgroundColor = UIColor.clearColor()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.title.addSubview(self.closeButton)
self.title.addSubview(self.titleText)
self.title.addSubview(self.favicon)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
backgroundHolder.addSubview(self.title)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
class TabTrayController: UIViewController, UITabBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var tabManager: TabManager!
private let CellIdentifier = "CellIdentifier"
var collectionView: UICollectionView!
var profile: Profile!
var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
var navBar: UIView!
var addTabButton: UIButton!
@available(iOS 9, *)
lazy var addPrivateTabButton: UIButton = {
let button = UIButton()
button.setTitle("P", forState: .Normal)
button.addTarget(self, action: "SELdidClickAddPrivateTab", forControlEvents: .TouchUpInside)
button.accessibilityLabel = NSLocalizedString("Add Private Tab", comment: "Accessibility labe for the Add Private Tab button in the Tab Tray.")
return button
}()
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
let signInButton = UIButton(type: UIButtonType.Custom)
signInButton.addTarget(self, action: "SELdidClickDone", forControlEvents: UIControlEvents.TouchUpInside)
signInButton.setTitle(NSLocalizedString("Sign in", comment: "Button that leads to Sign in section of the Settings sheet."), forState: UIControlState.Normal)
signInButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
// workaround for VoiceOver bug - if we create the button with UIButton.buttonWithType,
// it gets initial frame with height 0 and accessibility somehow does not update the height
// later and thus the button becomes completely unavailable to VoiceOver unless we
// explicitly set the height to some (reasonable) non-zero value.
// Also note that setting accessibilityFrame instead of frame has no effect.
signInButton.frame.size.height = signInButton.intrinsicContentSize().height
let navItem = UINavigationItem()
navItem.titleView = signInButton
signInButton.hidden = true //hiding sign in button until we decide on UX
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: CellIdentifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
if #available(iOS 9, *) {
view.addSubview(addPrivateTabButton)
addPrivateTabButton.snp_makeConstraints { make in
make.right.equalTo(addTabButton.snp_left).offset(-10)
make.size.equalTo(UIConstants.ToolbarHeight)
make.centerY.equalTo(self.navBar)
}
}
}
private func makeConstraints() {
let viewBindings: [String: AnyObject] = [
"topLayoutGuide" : topLayoutGuide,
"navBar" : navBar
]
let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraints)
navBar.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab()
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
@available(iOS 9, *)
func SELdidClickAddPrivateTab() {
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab(isPrivate: true)
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let tab = tabManager[indexPath.item]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! TabCell
cell.animator.delegate = self
cell.delegate = self
if let tab = tabManager[indexPath.item] {
cell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
cell.accessibilityLabel = tab.displayTitle
} else {
cell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
cell.isAccessibilityElement = true
cell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
cell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
cell.favicon.image = UIImage(named: "defaultFavicon")
}
cell.background.image = tab.screenshot
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabManager.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = self.collectionView.indexPathForCell(tabCell) {
if let tab = tabManager[indexPath.item] {
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
// Our UI doesn't care about what's selected
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex index: Int, restoring: Bool) {
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tabManager[index])
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int) {
self.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
self.collectionView.reloadItemsAtIndexPaths(self.collectionView.indexPathsForVisibleItems())
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
if let tab = tabManager[indexPath.item] {
tabManager.removeTab(tab)
}
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sortInPlace { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
private override func collectionViewContentSize() -> CGSize {
var calculatedSize = super.collectionViewContentSize()
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
|
mpl-2.0
|
4acdc494644c230ef1129e0ddb22a809
| 43.318919 | 304 | 0.700248 | 5.576287 | false | false | false | false |
mapsme/omim
|
iphone/Maps/Classes/Components/RatingView/RatingView.swift
|
5
|
17863
|
@IBDesignable final class RatingView: UIView {
@IBInspectable var value: CGFloat = RatingViewSettings.Default.value {
didSet {
guard oldValue != value else { return }
let clamped = min(CGFloat(settings.starsCount), max(0, value))
if clamped == value {
update()
} else {
value = clamped
}
}
}
@IBInspectable var leftText: String? {
get { return texts[.left] }
set { texts[.left] = newValue }
}
@IBInspectable var leftTextColor: UIColor {
get { return settings.textColors[.left]! }
set {
settings.textColors[.left] = newValue
update()
}
}
var leftTextFont: UIFont {
get { return settings.textFonts[.left]! }
set {
settings.textFonts[.left] = newValue
update()
}
}
@IBInspectable var leftTextSize: CGFloat {
get { return settings.textSizes[.left]! }
set {
settings.textSizes[.left] = newValue
update()
}
}
@IBInspectable var leftTextMargin: CGFloat {
get { return settings.textMargins[.left]! }
set {
settings.textMargins[.left] = newValue
update()
}
}
@IBInspectable var rightText: String? {
get { return texts[.right] }
set { texts[.right] = newValue }
}
@IBInspectable var rightTextColor: UIColor {
get { return settings.textColors[.right]! }
set {
settings.textColors[.right] = newValue
update()
}
}
var rightTextFont: UIFont {
get { return settings.textFonts[.right]! }
set {
settings.textFonts[.right] = newValue
update()
}
}
@IBInspectable var rightTextSize: CGFloat {
get { return settings.textSizes[.right]! }
set {
settings.textSizes[.right] = newValue
update()
}
}
@IBInspectable var rightTextMargin: CGFloat {
get { return settings.textMargins[.right]! }
set {
settings.textMargins[.right] = newValue
update()
}
}
@IBInspectable var topText: String? {
get { return texts[.top] }
set { texts[.top] = newValue }
}
@IBInspectable var topTextColor: UIColor {
get { return settings.textColors[.top]! }
set {
settings.textColors[.top] = newValue
update()
}
}
var topTextFont: UIFont {
get { return settings.textFonts[.top]! }
set {
settings.textFonts[.top] = newValue
update()
}
}
@IBInspectable var topTextSize: CGFloat {
get { return settings.textSizes[.top]! }
set {
settings.textSizes[.top] = newValue
update()
}
}
@IBInspectable var topTextMargin: CGFloat {
get { return settings.textMargins[.top]! }
set {
settings.textMargins[.top] = newValue
update()
}
}
@IBInspectable var bottomText: String? {
get { return texts[.bottom] }
set { texts[.bottom] = newValue }
}
@IBInspectable var bottomTextColor: UIColor {
get { return settings.textColors[.bottom]! }
set {
settings.textColors[.bottom] = newValue
update()
}
}
var bottomTextFont: UIFont {
get { return settings.textFonts[.bottom]! }
set {
settings.textFonts[.bottom] = newValue
update()
}
}
@IBInspectable var bottomTextSize: CGFloat {
get { return settings.textSizes[.bottom]! }
set {
settings.textSizes[.bottom] = newValue
update()
}
}
@IBInspectable var bottomTextMargin: CGFloat {
get { return settings.textMargins[.bottom]! }
set {
settings.textMargins[.bottom] = newValue
update()
}
}
private var texts: [RatingViewSettings.TextSide: String] = [:] {
didSet { update() }
}
@IBInspectable var starType: Int {
get { return settings.starType.rawValue }
set {
settings.starType = RatingViewSettings.StarType(rawValue: newValue) ?? RatingViewSettings.Default.starType
settings.starPoints = RatingViewSettings.Default.starPoints[settings.starType]!
update()
}
}
@IBInspectable var starsCount: Int {
get { return settings.starsCount }
set {
settings.starsCount = newValue
update()
}
}
@IBInspectable var starSize: CGFloat {
get { return settings.starSize }
set {
settings.starSize = newValue
update()
}
}
@IBInspectable var starMargin: CGFloat {
get { return settings.starMargin }
set {
settings.starMargin = newValue
update()
}
}
@IBInspectable var filledColor: UIColor {
get { return settings.filledColor }
set {
settings.filledColor = newValue
update()
}
}
@IBInspectable var emptyColor: UIColor {
get { return settings.emptyColor }
set {
settings.emptyColor = newValue
update()
}
}
@IBInspectable var emptyBorderColor: UIColor {
get { return settings.emptyBorderColor }
set {
settings.emptyBorderColor = newValue
update()
}
}
@IBInspectable var borderWidth: CGFloat {
get { return settings.borderWidth }
set {
settings.borderWidth = newValue
update()
}
}
@IBInspectable var filledBorderColor: UIColor {
get { return settings.filledBorderColor }
set {
settings.filledBorderColor = newValue
update()
}
}
@IBInspectable var fillMode: Int {
get { return settings.fillMode.rawValue }
set {
settings.fillMode = RatingViewSettings.FillMode(rawValue: newValue) ?? RatingViewSettings.Default.fillMode
update()
}
}
@IBInspectable var minTouchRating: CGFloat {
get { return settings.minTouchRating }
set {
settings.minTouchRating = newValue
update()
}
}
@IBInspectable var filledImage: UIImage? {
get { return settings.filledImage }
set {
settings.filledImage = newValue
update()
}
}
@IBInspectable var emptyImage: UIImage? {
get { return settings.emptyImage }
set {
settings.emptyImage = newValue
update()
}
}
@IBOutlet weak var delegate: RatingViewDelegate?
var settings = RatingViewSettings() {
didSet {
update()
}
}
private let isRightToLeft = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
public override func awakeFromNib() {
super.awakeFromNib()
setup()
update()
}
public convenience init() {
self.init(frame: CGRect())
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
update()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
update()
}
private func setup() {
layer.backgroundColor = UIColor.clear.cgColor
isOpaque = true
}
private var viewSize = CGSize()
private var scheduledUpdate: DispatchWorkItem?
func updateImpl() {
let layers = createLayers()
layer.sublayers = layers
viewSize = calculateSizeToFitLayers(layers)
invalidateIntrinsicContentSize()
frame.size = intrinsicContentSize
}
func update() {
scheduledUpdate?.cancel()
scheduledUpdate = DispatchWorkItem { [weak self] in self?.updateImpl() }
DispatchQueue.main.async(execute: scheduledUpdate!)
}
override var intrinsicContentSize: CGSize {
return viewSize
}
private func createLayers() -> [CALayer] {
return combineLayers(starLayers: createStarLayers(), textLayers: createTextLayers())
}
private func combineLayers(starLayers: [CALayer], textLayers: [RatingViewSettings.TextSide: CALayer]) -> [CALayer] {
var layers = starLayers
var starsWidth: CGFloat = 0
layers.forEach { starsWidth = max(starsWidth, $0.position.x + $0.bounds.width) }
if let topTextLayer = textLayers[.top] {
topTextLayer.position = CGPoint()
var topTextLayerSize = topTextLayer.bounds.size
topTextLayerSize.width = max(topTextLayerSize.width, starsWidth)
topTextLayer.bounds.size = topTextLayerSize
let y = topTextLayer.position.y + topTextLayer.bounds.height + topTextMargin
layers.forEach { $0.position.y += y }
}
if let bottomTextLayer = textLayers[.bottom] {
bottomTextLayer.position = CGPoint()
var bottomTextLayerSize = bottomTextLayer.bounds.size
bottomTextLayerSize.width = max(bottomTextLayerSize.width, starsWidth)
bottomTextLayer.bounds.size = bottomTextLayerSize
let star = layers.first!
bottomTextLayer.position.y = star.position.y + star.bounds.height + bottomTextMargin
}
let leftTextLayer: CALayer?
let leftMargin: CGFloat
let rightTextLayer: CALayer?
let rightMargin: CGFloat
if isRightToLeft {
leftTextLayer = textLayers[.right]
leftMargin = rightTextMargin
rightTextLayer = textLayers[.left]
rightMargin = leftTextMargin
} else {
leftTextLayer = textLayers[.left]
leftMargin = leftTextMargin
rightTextLayer = textLayers[.right]
rightMargin = rightTextMargin
}
if let leftTextLayer = leftTextLayer {
leftTextLayer.position = CGPoint()
let star = layers.first!
leftTextLayer.position.y = star.position.y + (star.bounds.height - leftTextLayer.bounds.height) / 2
let x = leftTextLayer.position.x + leftTextLayer.bounds.width + leftMargin
layers.forEach { $0.position.x += x }
textLayers[.top]?.position.x += x
textLayers[.bottom]?.position.x += x
}
if let rightTextLayer = rightTextLayer {
rightTextLayer.position = CGPoint()
let star = layers.last!
rightTextLayer.position = CGPoint(x: star.position.x + star.bounds.width + rightMargin,
y: star.position.y + (star.bounds.height - rightTextLayer.bounds.height) / 2)
}
layers.append(contentsOf: textLayers.values)
return layers
}
private func createStarLayers() -> [CALayer] {
var ratingRemainder = value
var starLayers: [CALayer] = (0 ..< settings.starsCount).map { _ in
let fillLevel = starFillLevel(ratingRemainder: ratingRemainder)
let layer = createCompositeStarLayer(fillLevel: fillLevel)
ratingRemainder -= 1
return layer
}
if isRightToLeft {
starLayers.reverse()
}
positionStarLayers(starLayers)
return starLayers
}
private func positionStarLayers(_ layers: [CALayer]) {
var positionX: CGFloat = 0
layers.forEach {
$0.position.x = positionX
positionX += $0.bounds.width + settings.starMargin
}
}
private func createTextLayers() -> [RatingViewSettings.TextSide: CALayer] {
var layers: [RatingViewSettings.TextSide: CALayer] = [:]
for (side, text) in texts {
let font = settings.textFonts[side]!.withSize(settings.textSizes[side]!)
let size = NSString(string: text).size(withAttributes: [NSAttributedString.Key.font: font])
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(),
size: CGSize(width: ceil(size.width), height: ceil(size.height)))
layer.anchorPoint = CGPoint()
layer.string = text
layer.font = CGFont(font.fontName as CFString)
layer.fontSize = font.pointSize
layer.foregroundColor = settings.textColors[side]!.cgColor
layer.contentsScale = UIScreen.main.scale
layers[side] = layer
}
return layers
}
private func starFillLevel(ratingRemainder: CGFloat) -> CGFloat {
guard ratingRemainder < 1 else { return 1 }
guard ratingRemainder > 0 else { return 0 }
switch settings.fillMode {
case .full: return round(ratingRemainder)
case .half: return round(ratingRemainder * 2) / 2
case .precise: return ratingRemainder
}
}
private func calculateSizeToFitLayers(_ layers: [CALayer]) -> CGSize {
var size = CGSize()
layers.forEach { layer in
size.width = max(size.width, layer.frame.maxX)
size.height = max(size.height, layer.frame.maxY)
}
return size
}
private func createCompositeStarLayer(fillLevel: CGFloat) -> CALayer {
guard fillLevel > 0 && fillLevel < 1 else { return createStarLayer(fillLevel >= 1) }
return createPartialStar(fillLevel: fillLevel)
}
func createPartialStar(fillLevel: CGFloat) -> CALayer {
let filledStar = createStarLayer(true)
let emptyStar = createStarLayer(false)
let parentLayer = CALayer()
parentLayer.contentsScale = UIScreen.main.scale
parentLayer.bounds = filledStar.bounds
parentLayer.anchorPoint = CGPoint()
parentLayer.addSublayer(emptyStar)
parentLayer.addSublayer(filledStar)
if isRightToLeft {
let rotation = CATransform3DMakeRotation(CGFloat.pi, 0, 1, 0)
filledStar.transform = CATransform3DTranslate(rotation, -filledStar.bounds.size.width, 0, 0)
}
filledStar.bounds.size.width *= fillLevel
return parentLayer
}
private func createStarLayer(_ isFilled: Bool) -> CALayer {
let size = settings.starSize
let containerLayer = createContainerLayer(size)
if let image = isFilled ? settings.filledImage : settings.emptyImage {
let imageLayer = createContainerLayer(size)
imageLayer.frame = containerLayer.bounds
imageLayer.contents = image.cgImage
imageLayer.contentsGravity = CALayerContentsGravity.resizeAspect
if image.renderingMode == .alwaysTemplate {
containerLayer.mask = imageLayer
containerLayer.backgroundColor = (isFilled ? settings.filledColor : settings.emptyColor).cgColor
} else {
containerLayer.addSublayer(imageLayer)
}
} else {
let fillColor = isFilled ? settings.filledColor : settings.emptyColor
let strokeColor = isFilled ? settings.filledBorderColor : settings.emptyBorderColor
let lineWidth = settings.borderWidth
let path = createStarPath(settings.starPoints, size: size, lineWidth: lineWidth)
let shapeLayer = createShapeLayer(path.cgPath,
lineWidth: lineWidth,
fillColor: fillColor,
strokeColor: strokeColor,
size: size)
containerLayer.addSublayer(shapeLayer)
}
return containerLayer
}
private func createContainerLayer(_ size: CGFloat) -> CALayer {
let layer = CALayer()
layer.contentsScale = UIScreen.main.scale
layer.anchorPoint = CGPoint()
layer.masksToBounds = true
layer.bounds.size = CGSize(width: size, height: size)
layer.isOpaque = true
return layer
}
private func createShapeLayer(_ path: CGPath, lineWidth: CGFloat, fillColor: UIColor, strokeColor: UIColor, size: CGFloat) -> CALayer {
let layer = CAShapeLayer()
layer.anchorPoint = CGPoint()
layer.contentsScale = UIScreen.main.scale
layer.strokeColor = strokeColor.cgColor
layer.fillRule = CAShapeLayerFillRule.evenOdd
layer.fillColor = fillColor.cgColor
layer.lineWidth = lineWidth
layer.lineJoin = CAShapeLayerLineJoin.round
layer.lineCap = CAShapeLayerLineCap.round
layer.bounds.size = CGSize(width: size, height: size)
layer.masksToBounds = true
layer.path = path
layer.isOpaque = true
return layer
}
private func createStarPath(_ starPoints: [CGPoint], size: CGFloat, lineWidth: CGFloat) -> UIBezierPath {
let sizeWithoutLineWidth = size - lineWidth * 2
let factor = sizeWithoutLineWidth / RatingViewSettings.Default.starPointsBoxSize
let points = starPoints.map { CGPoint(x: $0.x * factor + lineWidth,
y: $0.y * factor + lineWidth) }
let path: UIBezierPath
switch settings.starType {
case .regular:
path = UIBezierPath()
case .boxed:
path = UIBezierPath(roundedRect: CGRect(origin: CGPoint(), size: CGSize(width: size, height: size)), cornerRadius: size / 4)
}
path.move(to: points.first!)
points[1 ..< points.count].forEach { path.addLine(to: $0) }
path.close()
return path
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateImpl()
}
private func touchLocationFromBeginningOfRating(_ touches: Set<UITouch>) -> CGFloat? {
guard let touch = touches.first else { return nil }
var location = touch.location(in: self).x
let starLayers = layer.sublayers?.filter { !($0 is CATextLayer) }
var minX = bounds.width
var maxX: CGFloat = 0
starLayers?.forEach {
maxX = max(maxX, $0.position.x + $0.bounds.width)
minX = min(minX, $0.position.x)
}
assert(minX <= maxX)
if isRightToLeft {
location = maxX - location
} else {
location = location - minX
}
return location
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let location = touchLocationFromBeginningOfRating(touches) else { return }
onDidTouch(location)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let location = touchLocationFromBeginningOfRating(touches) else { return }
onDidTouch(location)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
delegate?.didFinishTouchingRatingView(self)
}
private func onDidTouch(_ location: CGFloat) {
guard let delegate = delegate else { return }
let prevRating = value
let starsCount = CGFloat(settings.starsCount)
let startsLength = settings.starSize * starsCount + (settings.starMargin * (starsCount - 1))
let percent = location / startsLength
let preciseRating = percent * starsCount
let fullStarts = floor(preciseRating)
let fractionRating = starFillLevel(ratingRemainder: preciseRating - fullStarts)
value = max(minTouchRating, fullStarts + fractionRating)
if prevRating != value {
delegate.didTouchRatingView(self)
}
}
}
|
apache-2.0
|
da6bcd5e437aa8d3c2e87ad3683a6d39
| 27.535144 | 137 | 0.661143 | 4.416069 | false | false | false | false |
Baichenghui/TestCode
|
FoodTracker/FoodTracker/MealTableViewController.swift
|
1
|
5768
|
//
// MealTableViewController.swift
// FoodTracker
//
// Created by yiliao on 2016/11/16.
// Copyright © 2016年 coderbai. All rights reserved.
//
import UIKit
class MealTableViewController: UITableViewController {
// MARK: Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem
// Load any saved meals, otherwise load sample data.
if let savedMeals = loadMeals() {
meals += savedMeals
}
else{
// Load the sample data.
loadSampleMeals()
}
}
func loadSampleMeals() {
let photo1 = UIImage(named: "meal1")!
let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4)!
let photo2 = UIImage(named: "meal2")!
let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5)!
let photo3 = UIImage(named: "meal3")!
let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3)!
meals += [meal1, meal2, meal3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "MealTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MealTableViewCell
// Fetches the appropriate meal for the data source layout.
let meal = meals[indexPath.row]
// Configure the cell...
cell.nameLabel?.text = meal.name
cell.photoImageView?.image = meal.photo
cell.ratingControl?.rating = meal.rating
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
meals.remove(at: indexPath.row)
saveMeals()
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetail" {
let mealDetailViewController = segue.destination as! MealViewController
// Get the cell that generated this segue.
if let selectedMealCell = sender as? MealTableViewCell {
let indexPath = tableView.indexPath(for: selectedMealCell)!
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
}
}
else if segue.identifier == "AddItem" {
print("Adding new meal.")
}
}
@IBAction func unwindToMealList(withSender: UIStoryboardSegue) {
if let sourceViewController = withSender.source as? MealViewController,
let meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
// Add a new meal.
let newIndexPath = NSIndexPath(row: meals.count, section: 0)
meals.append(meal)
tableView.insertRows(at: [newIndexPath as IndexPath], with: .bottom)
}
// Save the meals.
saveMeals()
}
}
// MARK: NSCoding
func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path)
if !isSuccessfulSave {
print("Failed to save meals...")
}
}
func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal]
}
}
|
mit
|
9a02e749cea5c2b24b4ccb861edca902
| 33.112426 | 136 | 0.614224 | 5.138146 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Model/PickerTypes.swift
|
1
|
5651
|
//
// PickerTypes.swift
// HXPHPicker
//
// Created by Slience on 2021/1/7.
//
import Foundation
import Photos
/// 资源类型可选项
public struct PickerAssetOptions: OptionSet {
/// Photo 静态照片
public static let photo = PickerAssetOptions(rawValue: 1 << 0)
/// Video 视频
public static let video = PickerAssetOptions(rawValue: 1 << 1)
/// Gif 动图(包括静态图)
public static let gifPhoto = PickerAssetOptions(rawValue: 1 << 2)
/// LivePhoto 实况照片
public static let livePhoto = PickerAssetOptions(rawValue: 1 << 3)
public var isPhoto: Bool {
contains(.photo) || contains(.gifPhoto) || contains(.livePhoto)
}
public var isVideo: Bool {
contains(.video)
}
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
public enum PickerSelectMode: Int {
/// 单选模式
case single = 0
/// 多选模式
case multiple = 1
}
/// 资源列表Cell点击动作
public enum SelectionTapAction: Equatable {
/// 进入预览界面
case preview
/// 快速选择
/// - 点击资源时会直接选中,不会进入预览界面
case quickSelect
/// 打开编辑器
/// - 点击资源时如果可以编辑的话,就会进入编辑界面
case openEditor
}
public extension PickerResult {
struct Options: OptionSet {
public static let photo = Options(rawValue: 1 << 0)
public static let video = Options(rawValue: 1 << 1)
public static let any: Options = [.photo, .video]
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
}
public extension PhotoAsset {
enum MediaType: Int {
/// 照片
case photo = 0
/// 视频
case video = 1
}
enum MediaSubType: Equatable {
/// 手机相册里的图片
case image
/// 手机相册里的动图
case imageAnimated
/// 手机相册里的LivePhoto
case livePhoto
/// 手机相册里的视频
case video
/// 本地图片
case localImage
/// 本地视频
case localVideo
/// 本地LivePhoto
case localLivePhoto
/// 本地动图
case localGifImage
/// 网络图片
case networkImage(Bool)
/// 网络视频
case networkVideo
public var isLocal: Bool {
switch self {
case .localImage, .localGifImage, .localVideo, .localLivePhoto:
return true
default:
return false
}
}
public var isPhoto: Bool {
switch self {
case .image, .imageAnimated, .livePhoto, .localImage, .localLivePhoto, .localGifImage, .networkImage(_):
return true
default:
return false
}
}
public var isVideo: Bool {
switch self {
case .video, .localVideo, .networkVideo:
return true
default:
return false
}
}
public var isGif: Bool {
switch self {
case .imageAnimated, .localGifImage:
return true
case .networkImage(let isGif):
return isGif
default:
return false
}
}
public var isNetwork: Bool {
switch self {
case .networkImage(_), .networkVideo:
return true
default:
return false
}
}
}
enum DownloadStatus: Int {
/// 未知,不用下载或还未开始下载
case unknow
/// 下载成功
case succeed
/// 下载中
case downloading
/// 取消下载
case canceled
/// 下载失败
case failed
}
/// 网络视频加载方式
enum LoadNetworkVideoMode {
/// 先下载
case download
/// 直接播放
case play
}
}
public enum AlbumShowMode: Int {
/// 正常展示
case normal = 0
/// 弹出展示
case popup = 1
}
public extension PhotoPickerViewController {
enum CancelType {
/// 文本
case text
/// 图片
case image
}
enum CancelPosition {
/// 左边
case left
/// 右边
case right
}
}
public extension PhotoPreviewViewController {
enum PlayType {
/// 视频不自动播放
/// LivePhoto需要长按播放
case normal
/// 自动循环播放
case auto
/// 只有第一次自动播放
case once
}
}
public enum DonwloadURLType {
case thumbnail
case original
}
extension PhotoManager {
enum CameraAlbumLocal: String {
case identifier = "HXCameraAlbumLocalIdentifier"
case identifierType = "HXCameraAlbumLocalIdentifierType"
case language = "HXCameraAlbumLocalLanguage"
}
}
extension PickerAssetOptions {
var mediaTypes: [PHAssetMediaType] {
var result: [PHAssetMediaType] = []
if contains(.photo) || contains(.gifPhoto) || contains(.livePhoto) {
result.append(.image)
}
if contains(.video) {
result.append(.video)
}
return result
}
}
/// Sort 排序规则
public enum Sort: Equatable {
/// ASC 升序
case asc
/// DESC 降序
case desc
}
|
mit
|
6ebc2d7bf445acf049204bacb972d07b
| 20.826271 | 116 | 0.528441 | 4.542328 | false | false | false | false |
Zovfreullia/unit-4-assignments
|
HWFrom1-24(Recursion).playground/Contents.swift
|
1
|
1093
|
/*
Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth
*/
//1 Write without the recursion
func fib(n: Int) -> Int {
print("X")
if (n == 0 || n == 1) {
return 1
}
return fib(n - 1) + fib(n - 2)
}
func fibTest (num: Int) -> Int {
var xn = 0
var n1 = 0
var n2 = 1
print(n1)
print(n2)
for(var i = 2; i < num; i++){
xn = n1 + n2
print(xn)
n1 = n2
n2 = xn
}
return num
}
fibTest(5)
//2
/* HW */
var stepNum = 0
func tryStep() -> Int {
let stepCount = Int(arc4random_uniform(3)) - 1
stepNum += stepCount;
switch(stepCount) {
case -1: print("Ouch \(stepNum)")
case 1: print("Yay \(stepNum)")
default: print("Beep \(stepNum)")
}
return stepCount
}
func stepUp() {
let stepCounts = tryStep()
if (stepCounts == -1){
print("stepCount -1")
stepUp()
print("stepCount -1")
stepUp()
}
else if (stepCounts == 0){
stepUp()
}
}
stepUp()
|
mit
|
4f07ed1bd2700ba78060a3a0d96539cd
| 14.408451 | 122 | 0.520586 | 2.846354 | false | false | false | false |
xwu/swift
|
test/decl/protocol/protocols.swift
|
1
|
19869
|
// RUN: %target-typecheck-verify-swift -enable-objc-interop
protocol EmptyProtocol { }
protocol DefinitionsInProtocols {
init() {} // expected-error {{protocol initializers must not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
// Protocol decl.
protocol Test {
func setTitle(_: String)
func erase() -> Bool
var creator: String { get }
var major : Int { get }
var minor : Int { get }
var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{21-21= { get <#set#> \}}}
static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}} {{33-33= { get <#set#> \}}}
let bugfix // expected-error {{type annotation missing in pattern}} expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}}
var comment // expected-error {{type annotation missing in pattern}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol Test2 {
var property: Int { get }
var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{20-20= { get <#set#> \}}}
static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{28-28= { get <#set#> \}}}
associatedtype mytype
associatedtype mybadtype = Int
associatedtype V : Test = // expected-error {{expected type in associated type declaration}} {{28-28= <#type#>}}
}
func test1() {
var v1: Test
var s: String
v1.setTitle(s)
v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}}
}
protocol Bogus : Int {}
// expected-error@-1{{inheritance from non-protocol, non-class type 'Int'}}
// expected-error@-2{{type 'Self' constrained to non-protocol, non-class type 'Int'}}
// Explicit conformance checks (successful).
protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}}
struct TestFormat { }
protocol FormattedPrintable : CustomStringConvertible {
func print(format: TestFormat)
}
struct X0 : Any, CustomStringConvertible {
func print() {}
}
class X1 : Any, CustomStringConvertible {
func print() {}
}
enum X2 : Any { }
extension X2 : CustomStringConvertible {
func print() {}
}
// Explicit conformance checks (unsuccessful)
struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}}
class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}}
enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}}
struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}}
func print(format: TestFormat) {}
}
// Protocol compositions in inheritance clauses
protocol Left {
func l() // expected-note {{protocol requires function 'l()' with type '() -> ()'; do you want to add a stub?}}
}
protocol Right {
func r() // expected-note {{protocol requires function 'r()' with type '() -> ()'; do you want to add a stub?}}
}
typealias Both = Left & Right
protocol Up : Both {
func u()
}
struct DoesNotConform : Up {
// expected-error@-1 {{type 'DoesNotConform' does not conform to protocol 'Left'}}
// expected-error@-2 {{type 'DoesNotConform' does not conform to protocol 'Right'}}
func u() {}
}
// Circular protocols
protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error {{protocol 'CircleMiddle' refines itself}}
// expected-note@-1 {{protocol 'CircleMiddle' declared here}}
protocol CircleStart : CircleEnd { func circle_start() } // expected-error {{protocol 'CircleStart' refines itself}}
// expected-note@-1 {{protocol 'CircleStart' declared here}}
protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note 2 {{protocol 'CircleEnd' declared here}}
protocol CircleEntry : CircleTrivial { }
protocol CircleTrivial : CircleTrivial { } // expected-error {{protocol 'CircleTrivial' refines itself}}
struct Circle {
func circle_start() {}
func circle_middle() {}
func circle_end() {}
}
func testCircular(_ circle: Circle) {
// FIXME: It would be nice if this failure were suppressed because the protocols
// have circular definitions.
_ = circle as CircleStart // expected-error{{value of type 'Circle' does not conform to 'CircleStart' in coercion}}
}
// <rdar://problem/14750346>
protocol Q : C, H { }
protocol C : E { }
protocol H : E { }
protocol E { }
//===----------------------------------------------------------------------===//
// Associated types
//===----------------------------------------------------------------------===//
protocol SimpleAssoc {
associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}}
}
struct IsSimpleAssoc : SimpleAssoc {
struct Associated {}
}
struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}}
protocol StreamWithAssoc {
associatedtype Element
func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}}
}
struct AnRange<Int> : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
// Okay: Word is a typealias for Int
struct AWordStreamType : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}}
typealias Element = Float
func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}}
}
// Okay: Infers Element == Int
struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc {
func get() -> Int {}
}
protocol SequenceViaStream {
associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}}
func makeIterator() -> SequenceStreamTypeType
}
struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ {
typealias Element = Int
var min : Int
var max : Int
var stride : Int
mutating func next() -> Int? {
if min >= max { return .none }
let prev = min
min += stride
return prev
}
typealias Generator = IntIterator
func makeIterator() -> IntIterator {
return self
}
}
extension IntIterator : SequenceViaStream {
typealias SequenceStreamTypeType = IntIterator
}
struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}}
typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}}
func makeIterator() -> Int {}
}
protocol GetATuple {
associatedtype Tuple
func getATuple() -> Tuple
}
struct IntStringGetter : GetATuple {
typealias Tuple = (i: Int, s: String)
func getATuple() -> Tuple {}
}
protocol ClassConstrainedAssocType {
associatedtype T : class
// expected-error@-1 {{'class' constraint can only appear on protocol declarations}}
// expected-note@-2 {{did you mean to write an 'AnyObject' constraint?}}{{22-27=AnyObject}}
}
//===----------------------------------------------------------------------===//
// Default arguments
//===----------------------------------------------------------------------===//
// FIXME: Actually make use of default arguments, check substitutions, etc.
protocol ProtoWithDefaultArg {
func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}}
}
struct HasNoDefaultArg : ProtoWithDefaultArg {
func increment(_: Int) {}
}
//===----------------------------------------------------------------------===//
// Variadic function requirements
//===----------------------------------------------------------------------===//
protocol IntMaxable {
func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}}
}
struct HasIntMax : IntMaxable {
func intmax(first: Int, rest: Int...) -> Int {}
}
struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}}
}
struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}}
}
//===----------------------------------------------------------------------===//
// 'Self' type
//===----------------------------------------------------------------------===//
protocol IsEqualComparable {
func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}}
}
struct HasIsEqual : IsEqualComparable {
func isEqual(other: HasIsEqual) -> Bool {}
}
struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}}
func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}}
}
//===----------------------------------------------------------------------===//
// Static methods
//===----------------------------------------------------------------------===//
protocol StaticP {
static func f()
}
protocol InstanceP {
func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}}
}
struct StaticS1 : StaticP {
static func f() {}
}
struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}}
static func f() {} // expected-note{{candidate operates on a type, not an instance as required}}
}
struct StaticAndInstanceS : InstanceP {
static func f() {}
func f() {}
}
func StaticProtocolFunc() {
let a: StaticP = StaticS1()
a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}}
}
func StaticProtocolGenericFunc<t : StaticP>(_: t) {
t.f()
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Eq {
static func ==(lhs: Self, rhs: Self) -> Bool
}
extension Int : Eq { }
// Matching prefix/postfix.
prefix operator <>
postfix operator <>
protocol IndexValue {
static prefix func <> (_ max: Self) -> Int
static postfix func <> (min: Self) -> Int
}
prefix func <> (max: Int) -> Int { return 0 }
postfix func <> (min: Int) -> Int { return 0 }
extension Int : IndexValue {}
//===----------------------------------------------------------------------===//
// Class protocols
//===----------------------------------------------------------------------===//
protocol IntrusiveListNode : class {
var next : Self { get }
}
final class ClassNode : IntrusiveListNode {
var next : ClassNode = ClassNode()
}
struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNode // expected-error {{value type 'StructNode' cannot have a stored property that recursively contains it}}
}
final class ClassNodeByExtension { }
struct StructNodeByExtension { }
extension ClassNodeByExtension : IntrusiveListNode {
var next : ClassNodeByExtension {
get {
return self
}
set {}
}
}
extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNodeByExtension {
get {
return self
}
set {}
}
}
final class GenericClassNode<T> : IntrusiveListNode {
var next : GenericClassNode<T> = GenericClassNode()
}
struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}}
var next : GenericStructNode<T> // expected-error {{value type 'GenericStructNode<T>' cannot have a stored property that recursively contains it}}
}
// Refined protocols inherit class-ness
protocol IntrusiveDListNode : IntrusiveListNode {
var prev : Self { get }
}
final class ClassDNode : IntrusiveDListNode {
var prev : ClassDNode = ClassDNode()
var next : ClassDNode = ClassDNode()
}
struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}}
// expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}}
var prev : StructDNode // expected-error {{value type 'StructDNode' cannot have a stored property that recursively contains it}}
var next : StructDNode
}
@objc protocol ObjCProtocol {
func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}}
}
protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}}
func bar()
}
class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}}
}
@objc protocol ObjCProtocolRefinement : ObjCProtocol { }
@objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}}
// <rdar://problem/16079878>
protocol P1 {
associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}}
}
protocol P2 {
}
struct X3<T : P1> where T.Assoc : P2 {}
struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}}
func getX1() -> X3<X4> { return X3() }
}
protocol ShouldntCrash {
// rdar://16109996
let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}}
// <rdar://problem/17200672> Let in protocol causes unclear errors and crashes
let fullName2: String // expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{3-6=var}} {{24-24= { get \}}}
// <rdar://problem/16789886> Assert on protocol property requirement without a type
var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}}
// expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}}
}
// rdar://problem/18168866
protocol FirstProtocol {
// expected-warning@+1 {{'weak' cannot be applied to a property declaration in a protocol; this is an error in Swift 5}}
weak var delegate : SecondProtocol? { get } // expected-error{{'weak' must not be applied to non-class-bound 'SecondProtocol'; consider adding a protocol conformance that has a class bound}}
}
protocol SecondProtocol {
func aMethod(_ object : FirstProtocol)
}
// <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing
class C1 : P2 {}
func f<T : C1>(_ x : T) {
_ = x as P2
}
class C2 {}
func g<T : C2>(_ x : T) {
x as P2 // expected-error{{value of type 'T' does not conform to 'P2' in coercion}}
}
class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}}
func h<T : C3>(_ x : T) {
_ = x as P1
}
func i<T : C3>(_ x : T?) -> Bool {
return x is P1
// FIXME: Bogus diagnostic. See SR-11920.
// expected-warning@-2 {{checking a value with optional type 'T?' against dynamic type 'P1' succeeds whenever the value is non-nil; did you mean to use '!= nil'?}}
}
func j(_ x : C1) -> Bool {
return x is P1
}
func k(_ x : C1?) -> Bool {
return x is P1
}
protocol P4 {
associatedtype T // expected-note {{protocol requires nested type 'T'}}
}
class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}}
associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}}
}
// <rdar://problem/25185722> Crash with invalid 'let' property in protocol
protocol LetThereBeCrash {
let x: Int
// expected-error@-1 {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{13-13= { get \}}}
// expected-note@-2 {{declared here}}
let xs: [Int]
// expected-error@-1 {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{3-6=var}} {{16-16= { get \}}}
// expected-note@-2 {{declared here}}
}
extension LetThereBeCrash {
init() { x = 1; xs = [] }
// expected-error@-1 {{'let' property 'x' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
// expected-error@-2 {{'let' property 'xs' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
// SR-11412
// Offer fix-it to conform type of context to the missing protocols
protocol SR_11412_P1 {}
protocol SR_11412_P2 {}
protocol SR_11412_P3 {}
protocol SR_11412_P4: AnyObject {}
class SR_11412_C0 {
var foo1: SR_11412_P1?
var foo2: (SR_11412_P1 & SR_11412_P2)?
weak var foo3: SR_11412_P4?
}
// Context has no inherited types and does not conform to protocol //
class SR_11412_C1 {
let c0 = SR_11412_C0()
func conform() {
c0.foo1 = self // expected-error {{cannot assign value of type 'SR_11412_C1' to type 'SR_11412_P1?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1' to class 'SR_11412_C1'}}{{18-18=: SR_11412_P1}}
}
}
// Context has no inherited types and does not conform to protocol composition //
class SR_11412_C2 {
let c0 = SR_11412_C0()
func conform() {
c0.foo2 = self // expected-error {{cannot assign value of type 'SR_11412_C2' to type '(SR_11412_P1 & SR_11412_P2)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1 & SR_11412_P2' to class 'SR_11412_C2'}}{{18-18=: SR_11412_P1 & SR_11412_P2}}
}
}
// Context already has an inherited type, but does not conform to protocol //
class SR_11412_C3: SR_11412_P3 {
let c0 = SR_11412_C0()
func conform() {
c0.foo1 = self // expected-error {{cannot assign value of type 'SR_11412_C3' to type 'SR_11412_P1?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1' to class 'SR_11412_C3'}}{{31-31=, SR_11412_P1}}
}
}
// Context conforms to only one protocol in the protocol composition //
class SR_11412_C4: SR_11412_P1 {
let c0 = SR_11412_C0()
func conform() {
c0.foo2 = self // expected-error {{cannot assign value of type 'SR_11412_C4' to type '(SR_11412_P1 & SR_11412_P2)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1 & SR_11412_P2' to class 'SR_11412_C4'}}{{31-31=, SR_11412_P2}}
}
}
// Context is a value type, but protocol requires class //
struct SR_11412_S0 {
let c0 = SR_11412_C0()
func conform() {
c0.foo3 = self // expected-error {{cannot assign value of type 'SR_11412_S0' to type 'SR_11412_P4?'}}
}
}
|
apache-2.0
|
24b2f20da89e1afc636a934cdd56084d
| 35.323583 | 232 | 0.658362 | 4.064853 | false | false | false | false |
Allow2CEO/browser-ios
|
brave/src/data/FaviconMO.swift
|
1
|
2390
|
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import CoreData
import Foundation
import Storage
class FaviconMO: NSManagedObject {
@NSManaged var url: String?
@NSManaged var width: Int16
@NSManaged var height: Int16
@NSManaged var type: Int16
@NSManaged var domain: Domain?
// Necessary override due to bad classname, maybe not needed depending on future CD
static func entity(_ context: NSManagedObjectContext) -> NSEntityDescription {
return NSEntityDescription.entity(forEntityName: "Favicon", in: context)!
}
class func get(forFaviconUrl urlString: String, context: NSManagedObjectContext) -> FaviconMO? {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = FaviconMO.entity(context)
fetchRequest.predicate = NSPredicate(format: "url == %@", urlString)
var result: FaviconMO? = nil
do {
let results = try context.fetch(fetchRequest) as? [FaviconMO]
if let item = results?.first {
result = item
}
} catch {
let fetchError = error as NSError
print(fetchError)
}
return result
}
class func add(_ favicon: Favicon, forSiteUrl siteUrl: URL) {
let context = DataController.shared.workerContext
context.perform {
var item = FaviconMO.get(forFaviconUrl: favicon.url, context: context)
if item == nil {
item = FaviconMO(entity: FaviconMO.entity(context), insertInto: context)
item!.url = favicon.url
}
if item?.domain == nil {
item!.domain = Domain.getOrCreateForUrl(siteUrl, context: context)
}
let w = Int16(favicon.width ?? 0)
let h = Int16(favicon.height ?? 0)
let t = Int16(favicon.type.rawValue)
if w != item!.width && w > 0 {
item!.width = w
}
if h != item!.height && h > 0 {
item!.height = h
}
if t != item!.type {
item!.type = t
}
DataController.saveContext(context: context)
}
}
}
|
mpl-2.0
|
ce9eecf268d2c6a7c02cab2124901b10
| 33.637681 | 198 | 0.586611 | 4.789579 | false | false | false | false |
IcyButterfly/MappingAce
|
MappingAce/OptionalMapping.swift
|
2
|
1475
|
//
// OptionalMapping.swift
// Mapping
//
// Created by ET|冰琳 on 16/10/24.
// Copyright © 2016年 Ice Butterfly. All rights reserved.
//
import Foundation
extension Optional: ValueMapping{
public static func mappingWith(any: Any?) -> Any? {
if let value = any{
if let type = Wrapped.self as? ValueMapping.Type{
return type.mappingWith(any: value)
}
}
return nil
}
public func serializedValue() -> Any? {
guard let r = self else{
return nil
}
if let mapping = r as? ValueMapping{
return mapping.serializedValue()
}
return r
}
}
extension Optional: Initializable{
public static func initialize(pointer: UnsafeMutableRawPointer, offset: Int, value: Any?){
let p = pointer.advanced(by: offset)
let mapped = self.mappingWith(any: value)
let bind = p.bindMemory(to: Optional<Wrapped>.self, capacity: 1)
bind.initialize(to: mapped as? Wrapped)
}
}
extension Optional: Updatable{
public static func update(pointer: UnsafeMutableRawPointer, offset: Int, value: Any?){
let p = pointer.advanced(by: offset)
let mapped = self.mappingWith(any: value)
let bind = p.bindMemory(to: Optional<Wrapped>.self, capacity: 1)
bind.pointee = mapped as? Wrapped
}
}
|
mit
|
3c993c79446b9f4673c6864a697efb3c
| 23.466667 | 94 | 0.576294 | 4.408408 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/BahamutCommon/DateHelper.swift
|
1
|
10447
|
//
// DateHelper.swift
// BahamutRFKit
//
// Created by AlexChow on 15/8/8.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import Foundation
open class DateHelper
{
open static var UnixTimeSpanTotalMilliseconds:Int64{
return Int64(Date().timeIntervalSince1970 * 1000)
}
fileprivate static let accurateDateTimeFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
fileprivate static let dateFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
fileprivate static let dateTimeFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
fileprivate static let localDateTimeSimpleFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yy/MM/dd HH:mm"
formatter.timeZone = TimeZone.current
return formatter
}()
fileprivate static let localDateTimeFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone.current
return formatter
}()
fileprivate static let localDateFomatter:DateFormatter = {
var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone.current
return formatter
}()
open class func toDateString(_ date:Date) -> String
{
return dateFomatter.string(from: date)
}
open class func toAccurateDateTimeString(_ date:Date) -> String
{
return accurateDateTimeFomatter.string(from: date)
}
open class func toDateTimeString(_ date:Date) -> String
{
return dateTimeFomatter.string(from: date)
}
open class func stringToAccurateDate(_ accurateDateString:String!) -> Date!
{
if let d = accurateDateString
{
return accurateDateTimeFomatter.date(from: d)
}
return nil
}
open class func stringToDateTime(_ date:String!) -> Date!
{
if let d = date
{
return dateTimeFomatter.date(from: d)
}
return nil
}
open class func stringToDate(_ date:String!) -> Date!
{
if let d = date
{
return dateFomatter.date(from: d)
}
return nil
}
open class func toLocalDateTimeSimpleString(_ date:Date) -> String
{
return localDateTimeSimpleFomatter.string(from: date)
}
open class func toLocalDateTimeString(_ date:Date) -> String
{
return localDateTimeFomatter.string(from: date)
}
open class func toLocalDateString(_ date:Date) -> String
{
return localDateFomatter.string(from: date)
}
static let monthDays = [31,28,31,30,31,30,31,31,30,31,30,31]
open class func daysOfMonth(_ year:Int,month:Int) -> Int
{
let monthIndex = month > 0 ? month - 1 : 0
if monthIndex == 1
{
return monthDays[monthIndex] + (isLeapYear(year) ? 1 : 0)
}
return monthDays[monthIndex]
}
open class func isLeapYear(_ year:Int) -> Bool
{
if (year%4==0 && year % 100 != 0) || year%400==0 {
return true
}else {
return false
}
}
}
public extension String
{
public var dateTimeOfString:Date!{
return DateHelper.stringToDateTime(self)
}
public var dateTimeOfAccurateString:Date!{
return DateHelper.stringToAccurateDate(self)
}
}
public extension Date
{
public func toDateString() -> String
{
return DateHelper.toDateString(self)
}
public func toDateTimeString() -> String
{
return DateHelper.toDateTimeString(self)
}
public func toAccurateDateTimeString() -> String
{
return DateHelper.toAccurateDateTimeString(self)
}
public func toLocalDateString() -> String
{
return DateHelper.toLocalDateString(self)
}
public func toLocalDateTimeString() -> String
{
return DateHelper.toLocalDateTimeString(self)
}
public func toLocalDateTimeSimpleString() -> String
{
return DateHelper.toLocalDateTimeSimpleString(self)
}
}
public extension Date
{
var totalSecondsSince1970:NSNumber{
return NSNumber(value: timeIntervalSince1970 as Double)
}
var totalMinutesSince1970:NSNumber{
return NSNumber(value:totalSecondsSince1970.doubleValue / 60.0)
}
var totalHoursSince1970:NSNumber{
return NSNumber(value:totalMinutesSince1970.doubleValue / 60)
}
var totalDaysSince1970:NSNumber{
return NSNumber(value:totalHoursSince1970.doubleValue / 24)
}
var totalSecondsSinceNow:NSNumber{
return NSNumber(value: timeIntervalSinceNow as Double)
}
var totalMinutesSinceNow:NSNumber{
return NSNumber(value:totalSecondsSinceNow.doubleValue / 60)
}
var totalHoursSinceNow:NSNumber{
return NSNumber(value:totalMinutesSinceNow.doubleValue / 60)
}
var totalDaysSinceNow:NSNumber{
return NSNumber(value:totalHoursSinceNow.doubleValue / 24)
}
}
public extension Date
{
func addYears(_ years:Int) -> Date
{
return addDays(years * 365)
}
func addMonthes(_ monthes:Int) -> Date
{
return addDays(monthes * 30)
}
func addWeeks(_ weeks:Int) -> Date
{
return addDays(weeks * 7)
}
func addDays(_ days:Int) -> Date
{
return addHours(days * 24)
}
func addHours(_ hours:Int) -> Date
{
return self.addMinutes(hours * 60)
}
func addMinutes(_ minutes:Int) -> Date
{
return self.addSeconds(TimeInterval(minutes * 60))
}
func addSeconds(_ seconds:TimeInterval) -> Date
{
let copy = Date(timeIntervalSinceNow: self.timeIntervalSinceNow)
return copy.addingTimeInterval(seconds)
}
}
public extension Date
{
public func isAfter(_ date:Date) -> Bool
{
return self.timeIntervalSince1970 > date.timeIntervalSince1970
}
public func ge(_ date:Date) -> Bool
{
return self.timeIntervalSince1970 >= date.timeIntervalSince1970
}
public func isBefore(_ date:Date) -> Bool
{
return self.timeIntervalSince1970 < date.timeIntervalSince1970
}
public func le(_ date:Date) -> Bool
{
return self.timeIntervalSince1970 <= date.timeIntervalSince1970
}
}
public extension Date
{
public func toFriendlyString(_ formatter:DateFormatter! = nil) -> String
{
let interval = -self.timeIntervalSinceNow
if interval < 60
{
return "JUST_NOW".bahamutCommonLocalizedString
}
else if interval < 3600
{
let mins = String(format: "%.0f", abs(self.totalMinutesSinceNow.doubleValue))
return String(format:"X_MINUTES_AGO".bahamutCommonLocalizedString,mins)
}else if interval < 3600 * 24
{
let hours = String(format: "%.0f", abs(self.totalHoursSinceNow.doubleValue))
return String(format:"X_HOURS_AGO".bahamutCommonLocalizedString,hours)
}else if interval < 3600 * 24 * 7
{
let days = String(format: "%.0f", abs(self.totalDaysSinceNow.doubleValue))
return String(format:"X_DAYS_AGO".bahamutCommonLocalizedString,days)
}else if formatter == nil
{
return self.toLocalDateString()
}else
{
return formatter.string(from: self)
}
}
}
extension DateHelper
{
static func generateDate(_ year:Int = 1970,month:Int = 1,day:Int = 1,hour:Int = 0,minute:Int = 0, second:TimeInterval = 0) -> Date
{
var s = second
var M = month
var m = minute
var d = day
var h = hour
if hour < 0 || hour > 23{
h = 0
}
if minute > 60 || minute < 0 {
m = 0
}
if second > 60 || second < 0
{
s = 0
}
if month <= 0 || month > 12
{
M = 1
}
if day <= 0
{
d = 1
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
formatter.timeZone = TimeZone.current
let dateString = String(format: "%04d-%02d-%02d %02d:%02d:%06.3f", year,M,d,h,m,s)
return formatter.date(from: dateString)!
}
}
public extension Date
{
var hourOfDate:Int{
return currentTimeZoneComponents.hour!
}
var minuteOfDate:Int{
return currentTimeZoneComponents.minute!
}
var secondOfDate:Int{
return currentTimeZoneComponents.second!
}
var yearOfDate:Int{
return currentTimeZoneComponents.year!
}
var monthOfDate:Int{
return currentTimeZoneComponents.month!
}
var dayOfDate:Int{
return currentTimeZoneComponents.day!
}
var weekDayOfDate:Int{
return currentTimeZoneComponents.weekday!
}
var shortWeekdayOfDate:String{
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "EEE"
let timeStr = formatter.string(from: self)
return timeStr
}
var weekdayOfDate:String{
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "EEEE"
let timeStr = formatter.string(from: self)
return timeStr
}
var currentTimeZoneComponents:DateComponents
{
return Calendar.autoupdatingCurrent.dateComponents(in: TimeZone.current, from: self)
}
}
extension DateHelper{
static func unixTimeSpanMsToDate(timeSpanFromUnxiMS:Int64) -> Date{
return Date(timeIntervalSince1970: Double(timeSpanFromUnxiMS) / 1000)
}
}
|
mit
|
04941957c1c3288fd3fac0d955bd9f56
| 25.1125 | 134 | 0.608712 | 4.454158 | false | false | false | false |
vinivendra/jokr
|
jokr/Translators/JKRJavaTranslator.swift
|
1
|
4849
|
// doc
// test
class JKRJavaTranslator: JKRTranslator {
////////////////////////////////////////////////////////////////////////////
// MARK: Interface
init(writingWith writer: JKRWriter = JKRConsoleWriter()) {
self.writer = writer
}
static func create(writingWith writer: JKRWriter) -> JKRTranslator {
return JKRJavaTranslator(writingWith: writer)
}
func translate(program: JKRTreeProgram) throws {
do {
if let statements = program.statements {
changeFile("Main.java")
indentation = 0
write("public class Main {\n")
indentation += 1
addIntentation()
write("public static void main(String []args) {\n")
indentation += 1
writeWithStructure(statements)
indentation = 1
addIntentation()
write("}\n}\n")
}
// if let declarations = program.declarations {
// }
try writer.finishWriting()
}
catch (let error) {
throw error
}
}
////////////////////////////////////////////////////////////////////////////
// MARK: Implementation
private static let valueTypes = ["int", "float", "void"]
// Transpilation (general structure)
private var indentation = 0
private func writeWithStructure(_ statements: [JKRTreeStatement]) {
for statement in statements {
writeWithStructure(statement)
}
}
private func writeWithStructure(_ statement: JKRTreeStatement) {
addIntentation()
write(translate(statement))
// if let block = statement.block {
// write(" {\n")
// indentation += 1
// writeWithStructure(block)
// indentation -= 1
// addIntentation()
// write("}\n")
// }
}
// Translation (pieces of code)
private func translate(_ statement: JKRTreeStatement) -> String {
switch statement {
case let .assignment(assignment):
return translate(assignment)
case let .functionCall(functionCall):
return translate(functionCall)
case let .returnStm(returnStm):
return translate(returnStm)
}
}
private func translate(_ assignment: JKRTreeAssignment) -> String {
switch assignment {
case let .declaration(type, id, expression):
let typeText = string(for: type, withSpaces: true)
let idText = string(for: id)
let expressionText = translate(expression)
return "\(typeText)\(idText) = \(expressionText);\n"
case let .assignment(id, expression):
let idText = string(for: id)
let expressionText = translate(expression)
return "\(idText) = \(expressionText);\n"
}
}
private func translate(_ functionCall: JKRTreeFunctionCall) -> String {
if functionCall.id == "print" {
if functionCall.parameters.count == 0 {
return "System.out.format(\"Hello jokr!\\n\");\n"
}
else {
let format = functionCall.parameters.map {_ in "%d" }
.joined(separator: " ")
let parameters = functionCall.parameters.map(translate)
.joined(separator: ", ")
return "System.out.format(\"\(format)\\n\", \(parameters));\n"
}
}
return "\(string(for: functionCall.id))();\n"
}
private func translateHeader(
_ function: JKRTreeFunctionDeclaration) -> String {
let parameters = function.parameters.map(string(for:))
.joined(separator: ", ")
return "\(string(for: function.type)) \(string(for: function.id))(\(parameters))"
// swiftlint:disable:previous line_length
}
private func translate(_ returnStm: JKRTreeReturn) -> String {
let expression = translate(returnStm.expression)
return "return \(expression);\n"
}
private func translate(_ expression: JKRTreeExpression) -> String {
switch expression {
case let .int(int):
return string(for: int)
case let .parenthesized(innerExpression):
let innerExpressionText = translate(innerExpression)
return "(\(innerExpressionText))"
case let .operation(leftExpression, op, rightExpression):
let leftText = translate(leftExpression)
let rightText = translate(rightExpression)
return "\(leftText) \(op.text) \(rightText)"
case let .lvalue(id):
return string(for: id)
}
}
private func string(for parameter: JKRTreeParameterDeclaration) -> String {
return "\(string(for: parameter.type)) \(string(for: parameter.id))"
}
private func string(for type: JKRTreeType,
withSpaces: Bool = false) -> String {
let lowercased = type.text.lowercased()
let space = withSpaces ? " " : ""
let result: String
if JKRJavaTranslator.valueTypes.contains(lowercased) {
result = lowercased
}
else {
result = type.text
}
return result + space
}
func string(for id: JKRTreeID) -> String {
return id.text
}
func string(for int: JKRTreeInt) -> String {
return String(int.value)
}
// Writing
private let writer: JKRWriter
private func write(_ string: String) {
writer.write(string)
}
private func changeFile(_ string: String) {
writer.changeFile(string)
}
private func addIntentation() {
for _ in 0..<indentation {
write("\t")
}
}
}
|
apache-2.0
|
d02eb3ec5110a5259f5678471d83346f
| 24.255208 | 83 | 0.657661 | 3.506146 | false | false | false | false |
wenghengcong/Coderpursue
|
BeeFun/BeeFun/View/Stars/BFStarController+Data.swift
|
1
|
4614
|
//
// BFStarController+Data.swift
// BeeFun
//
// Created by WengHengcong on 26/09/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
import ObjectMapper
extension BFStarController {
override func request() {
super.request()
svc_requestFetchTags(reloadCurrentPageData: true)
}
override func reconnect() {
super.reconnect()
svc_requestFetchTags(reloadCurrentPageData: true)
}
// MARK: - 获取Tag数据
func svc_requestFetchTags(reloadCurrentPageData: Bool) {
let hud = JSMBHUDBridge.showHud(view: view)
if !UserManager.shared.needLoginAlert() {
_ = checkCurrentLoginState()
hud.hide(animated: true)
return
}
if let owner = UserManager.shared.login {
tagFilter.owner = owner
}
tagFilter.page = 1
tagFilter.pageSize = 100000
tagFilter.sord = "desc"
tagFilter.sidx = "name"
var dict: [String: Any] = [:]
do {
dict = try JSONSerialization.jsonObject(with: try JSONEncoder().encode(tagFilter), options: []) as! [String: Any]
} catch {
print("tag filter is error")
}
BeeFunProvider.sharedProvider.request(BeeFunAPI.getAllTags(filter: dict) ) { (result) in
hud.hide(animated: true)
switch result {
case let .success(response):
do {
if let allTag: GetAllTagResponse = Mapper<GetAllTagResponse>().map(JSONObject: try response.mapJSON()) {
if let code = allTag.codeEnum, code == BFStatusCode.bfOk {
if let data = allTag.data {
DispatchQueue.main.async {
self.handleGetAllTagsRequestResponse(data: data, reloadCurrentPageData: reloadCurrentPageData)
}
return
}
}
}
} catch {
}
self.showReloadView()
self.changeNavSegmentControl(index: self.navSegmentView!.selIndex)
case .failure:
self.showReloadView()
self.changeNavSegmentControl(index: self.navSegmentView!.selIndex)
}
}
}
/// 处理网络获取到的tag数据
func handleGetAllTagsRequestResponse(data: [ObjTag], reloadCurrentPageData: Bool) {
removeReloadView()
carouselContent.isHidden = false
starTags.removeAll()
if data.count > 0 {
self.starTags.insert("All", at: 0)
for tag in data {
self.starTags.append(tag.name!)
}
}
svc_customViewAfterGetTags()
if self.starTags.count > 0 && self.tagBar != nil {
self.tagBar.sectionTitles = self.starTags
self.svc_layoutAllTagsButton()
}
if reloadCurrentPageData {
// 重新加载页面数据
carouselContent.reloadData()
currentContentView()?.reloadNetworkData(force: true)
}
}
/// Get watched repos
func svc_getWatchedReposRequest(_ pageVal: Int) {
if !UserManager.shared.isLogin {
return
}
let username = UserManager.shared.login
if DeviceType.isPad {
watchPerpage = 25
}
let hud = JSMBHUDBridge.showHud(view: self.view)
Provider.sharedProvider.request( .userWatchedRepos( page:pageVal, perpage:watchPerpage, username:username!) ) { (result) -> Void in
print(result)
hud.hide(animated: true)
var message = kNoDataFoundTip
switch result {
case let .success(response):
do {
let repos: [ObjRepos] = try response.mapArray(ObjRepos.self)
if self.watchPageVal == 1 {
self.watchsData.removeAll()
self.watchsData = repos
} else {
self.watchsData += repos
}
self.watchedTableView.reloadData()
} catch {
JSMBHUDBridge.showError(message, view: self.view)
}
case .failure:
message = kNetworkErrorTip
JSMBHUDBridge.showError(message, view: self.view)
}
}
}
}
|
mit
|
21d61fade034251e92242305343424ea
| 32.844444 | 139 | 0.522215 | 4.855473 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Jetpack/Classes/NUX/JetpackPrologueStyleGuide.swift
|
1
|
5900
|
import UIKit
import WordPressAuthenticator
/// The colors in here intentionally do not support light or dark modes since they're the same on both.
///
struct JetpackPrologueStyleGuide {
// Background colors
// old
static let oldBackgroundColor = UIColor(red: 0.00, green: 0.11, blue: 0.18, alpha: 1.00)
// combined
static let backgroundColor = FeatureFlag.newJetpackLandingScreen.enabled ? .clear : oldBackgroundColor
// Gradient overlay colors
// new
static let newGradientColor = UIColor(light: .muriel(color: .jetpackGreen, .shade0), dark: .muriel(color: .jetpackGreen, .shade100))
// combined
static let gradientColor = FeatureFlag.newJetpackLandingScreen.enabled ? newGradientColor : oldBackgroundColor
// Continue with WordPress button colors
// old
static let oldContinueHighlightedFillColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 0.90)
// new
static let newContinueFillColor = UIColor(light: .muriel(color: .jetpackGreen, .shade50), dark: .white)
static let newContinueHighlightedFillColor = UIColor(light: .muriel(color: .jetpackGreen, .shade90), dark: whiteWithAlpha07)
static let newContinueTextColor = UIColor(light: .white, dark: .muriel(color: .jetpackGreen, .shade80))
// combined
static let continueFillColor = FeatureFlag.newJetpackLandingScreen.enabled ? newContinueFillColor : .white
static let continueHighlightedFillColor = FeatureFlag.newJetpackLandingScreen.enabled ? newContinueHighlightedFillColor : oldContinueHighlightedFillColor
static let continueTextColor = FeatureFlag.newJetpackLandingScreen.enabled ? newContinueTextColor : oldBackgroundColor
static let continueHighlightedTextColor = FeatureFlag.newJetpackLandingScreen.enabled ? whiteWithAlpha07 : oldBackgroundColor
// Enter your site address button
// old
static let oldSiteBorderColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 0.40)
static let newSiteTextColor = UIColor(light: .muriel(color: .jetpackGreen, .shade90), dark: .white)
static let newSiteHighlightedTextColor = UIColor(light: .muriel(color: .jetpackGreen, .shade50), dark: whiteWithAlpha07)
static let oldSiteHighlightedBorderColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 0.20)
// combined
static let siteFillColor = FeatureFlag.newJetpackLandingScreen.enabled ? .clear : oldBackgroundColor
static let siteBorderColor = FeatureFlag.newJetpackLandingScreen.enabled ? .clear : oldSiteBorderColor
static let siteTextColor = FeatureFlag.newJetpackLandingScreen.enabled ? newSiteTextColor : UIColor.white
static let siteHighlightedFillColor = FeatureFlag.newJetpackLandingScreen.enabled ? whiteWithAlpha07 : oldBackgroundColor
static let siteHighlightedBorderColor = FeatureFlag.newJetpackLandingScreen.enabled ? whiteWithAlpha07 : oldSiteHighlightedBorderColor
static let siteHighlightedTextColor = FeatureFlag.newJetpackLandingScreen.enabled ? newSiteHighlightedTextColor : whiteWithAlpha07
// Color used in both old and versions
static let whiteWithAlpha07 = UIColor.white.withAlphaComponent(0.7)
// Background image with gradient for the new Jetpack prologue screen
static let prologueBackgroundImage: UIImage? = FeatureFlag.newJetpackLandingScreen.enabled ? UIImage(named: "JPBackground") : nil
// Blur effect for the prologue buttons
static let prologueButtonsBlurEffect: UIBlurEffect? = FeatureFlag.newJetpackLandingScreen.enabled ? UIBlurEffect(style: .regular) : nil
struct Title {
static let font: UIFont = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
static let textColor: UIColor = .white
}
struct Stars {
static let particleImage = UIImage(named: "circle-particle")
static let colors = [
UIColor(red: 0.05, green: 0.27, blue: 0.44, alpha: 1.00),
UIColor(red: 0.64, green: 0.68, blue: 0.71, alpha: 1.00),
UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: 1.00)
]
}
static let continueButtonStyle = NUXButtonStyle(normal: .init(backgroundColor: continueFillColor,
borderColor: continueFillColor,
titleColor: continueTextColor),
highlighted: .init(backgroundColor: continueHighlightedFillColor,
borderColor: continueHighlightedFillColor,
titleColor: continueHighlightedTextColor),
disabled: .init(backgroundColor: .white,
borderColor: .white,
titleColor: backgroundColor))
static let siteAddressButtonStyle = NUXButtonStyle(normal: .init(backgroundColor: siteFillColor,
borderColor: siteBorderColor,
titleColor: siteTextColor),
highlighted: .init(backgroundColor: siteHighlightedFillColor,
borderColor: siteHighlightedBorderColor,
titleColor: siteHighlightedTextColor),
disabled: .init(backgroundColor: .white,
borderColor: .white,
titleColor: backgroundColor))
}
|
gpl-2.0
|
05bb5a04e1d20fcd012f2b52ad62fddd
| 59.204082 | 157 | 0.63 | 5.452865 | false | false | false | false |
imxieyi/iosu
|
iosu/StoryBoard/MovingImage.swift
|
1
|
1732
|
//
// MovingImage.swift
// iosu
//
// Created by xieyi on 2017/5/16.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import SpriteKit
class MovingImage:BasicImage {
var framecount:Int
var framedelay:Double
var looptype:LoopType
var paths:[String]=[]
init(layer:SBLayer,rlayer:Double,origin:SBOrigin,filepath:String,x:Double,y:Double,framecount:Int,framedelay:Double,looptype:LoopType) {
self.framecount=framecount
self.framedelay=framedelay
self.looptype=looptype
super.init(layer: layer, rlayer: rlayer, origin: origin, filepath: filepath, x: x, y: y,isanimation:true)
}
override func convertsprite() {
let ext=filepath.components(separatedBy: ".").last
let extlen=ext?.lengthOfBytes(using: .utf8)
for i in 0...framecount-1 {
var path=filepath.substring(to:filepath.index(filepath.endIndex, offsetBy: -(extlen!+1)))
path+="\(i)."+ext!
paths.append(path)
}
filepath=paths.first!
super.convertsprite()
}
func animate(){
var textures:[SKTexture]=[]
for path in paths {
let image=ImageBuffer.get(path)
if(image==nil){
continue
}
textures.append(image!)
}
if(textures.count==0){
return
}
var animateaction=SKAction.animate(with: textures, timePerFrame: framedelay/1000)
switch looptype {
case .loopForever:
animateaction=SKAction.repeatForever(animateaction)
case .loopOnce:
break
}
actions=SKAction.group([animateaction,actions!])
}
}
|
mit
|
bb401bfd35799dda6b4b5ebd2264ea1d
| 27.816667 | 140 | 0.60266 | 3.993072 | false | false | false | false |
oisinlavery/HackingWithSwift
|
project9-oisin/project7-oisin/DetailViewController.swift
|
2
|
748
|
import UIKit
import WebKit
class DetailViewController: UIViewController {
var webView: WKWebView!
var detailItem: [String: String]!
override func loadView() {
webView = WKWebView()
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
guard detailItem != nil else { return }
if let body = detailItem["body"] {
print(body)
var html = "<html>"
html += "<head>"
html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
html += "<style> body { font-size: 150%; } </style>"
html += "</head>"
html += "<body>"
html += body
html += "</body>"
html += "</html>"
webView.loadHTMLString(html, baseURL: nil)
}
}
}
|
unlicense
|
bc09f51a72027c617fe89d235d4fb949
| 21.69697 | 88 | 0.578877 | 4.202247 | false | false | false | false |
kickstarter/ios-oss
|
Library/String+SimpleHTML.swift
|
1
|
4870
|
import Foundation
import UIKit
public extension String {
typealias Attributes = [NSAttributedString.Key: Any]
/**
Interprets `self` as an HTML string to produce an attributed string.
- parameter base: The base attributes to use for the attributed string.
- parameter bold: Optional attributes to use on bold tags. If not specified it will be derived
from `font`.
- parameter italic: Optional attributes for use on italic tags. If not specified it will be derived
from `font`.
- returns: The attributed string, or `nil` if something goes wrong with interpreting the string
as html.
*/
func simpleHtmlAttributedString(
base: Attributes,
bold optionalBold: Attributes? = nil,
italic optionalItalic: Attributes? = nil
) -> NSAttributedString? {
func parsedHtml() -> NSAttributedString? {
let baseFont = (base[NSAttributedString.Key.font] as? UIFont) ?? UIFont.systemFont(ofSize: 12.0)
// If bold or italic are not specified we can derive them from `font`.
let bold = optionalBold ?? [NSAttributedString.Key.font: baseFont.bolded]
let italic = optionalItalic ?? [NSAttributedString.Key.font: baseFont.italicized]
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
]
guard let string = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
else {
return nil
}
// Sub all bold and italic fonts in the attributed html string
let stringRange = NSRange(location: 0, length: string.length)
string.beginEditing()
string
.enumerateAttribute(NSAttributedString.Key.font, in: stringRange, options: []) { value, range, _ in
guard let htmlFont = value as? UIFont else { return }
let newAttributes: Attributes
if htmlFont.fontDescriptor.symbolicTraits.contains(.traitBold) {
newAttributes = bold
} else if htmlFont.fontDescriptor.symbolicTraits.contains(.traitItalic) {
newAttributes = italic
} else {
newAttributes = base
}
string.addAttributes(newAttributes, range: range)
}
string.endEditing()
return string
}
if Thread.isMainThread {
return parsedHtml()
} else {
return DispatchQueue.main.sync {
parsedHtml()
}
}
}
/**
Interprets `self` as an HTML string to produce an attributed string.
- parameter font: The base font to use for the attributed string.
- parameter bold: An optional font for bolding. If not specified it will be derived from `font`.
- parameter italic: An optional font for italicizing. If not specified it will be derived
from `font`.
- returns: The attributed string, or `nil` if something goes wrong with interpreting the string
as html.
*/
func simpleHtmlAttributedString(
font: UIFont,
bold optionalBold: UIFont? = nil,
italic optionalItalic: UIFont? = nil
) -> NSAttributedString? {
return self.simpleHtmlAttributedString(
base: [NSAttributedString.Key.font: font],
bold: optionalBold.flatMap { [NSAttributedString.Key.font: $0] },
italic: optionalItalic.flatMap { [NSAttributedString.Key.font: $0] }
)
}
/**
Removes all HTML from `self`.
- parameter trimWhitespace: If `true`, then all whitespace will be trimmed from the stripped string.
Defaults to `true`.
- returns: A string with all HTML stripped.
*/
func htmlStripped(trimWhitespace: Bool = true) -> String? {
func parsedHtml() -> String? {
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
]
let string = try? NSAttributedString(data: data, options: options, documentAttributes: nil)
let result = string?.string
if trimWhitespace {
return result?.trimmingCharacters(in: .whitespacesAndNewlines)
}
return result
}
if Thread.isMainThread {
return parsedHtml()
} else {
return DispatchQueue.main.sync {
parsedHtml()
}
}
}
}
// MARK: - Functions
func == (lhs: String.Attributes, rhs: String.Attributes) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
|
apache-2.0
|
e347836b770e6338bfb0e2f40f9a8c56
| 34.289855 | 110 | 0.677823 | 4.78389 | false | false | false | false |
shirai/SwiftLearning
|
playground/構造体.playground/Contents.swift
|
1
|
2323
|
//: Playground - noun: a place where people can play
import UIKit
/*
*カプセル化を実現する方法としてSwiftには、クラスの他に構造体(struct)が用意されています。但し、クラスと構造体には次のような違いがあります。
構造体では継承は利用できません。
構造体にデイニシャライザは定義できません。
クラスのインスタンスを別の変数に代入すると参照が渡されます。インスタンスの参照数は参照カウントで管理されます。対して構造体を別の変数に代入すると新たなコピーが生成されます。構造体の参照先は常に1つなので参照カウントは使用されません。
*/
struct Author {
var name: String = "不明"
var birthday: Date?
}
let author = Author()
print (author)
//構造体はメンバ変数を引数にもつイニシャライザが自動的に生成される
struct Author2 {
var name: String
var birthday: Date?
}
let formatter = DateFormatter()
formatter.dateFormat = "Y/M/d"
var author2 = Author2(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
print(author2)
//プロパティへのアクセスはクラスの場合と同様、.(ドット)を使う
print("著者:" + author2.name)
author2.name = "森鴎外"
author2.birthday = formatter.date(from: "1862/2/17")
print("著者:" + author2.name)
//構造体のメンバに構造体が含まれる場合は次の様に.(ドット)で繋いでアクセス
/* 書籍 */
struct Book {
var title: String
var author: Author
}
let book = Book(
title: "吾輩は猫である",
author: Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
)
print("書籍名:\(book.title), 著者:\(book.author.name)")
//定数として宣言した構造体のプロパティを変更することはできない。
let author3 = Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
//author3.name = "森鴎外"
var book1 = Book(title: "坊ちゃん", author: author)
var book2 = book1 //別の変数に代入した構造体のプロパティを変更しても、元の構造体のプロパティの値は変わらない。
book2.title = "吾輩は猫である"
print(book1.title)
print(book2.title)
|
mit
|
063498705add5a4e4ad8f68d0c95c9e1
| 23.05 | 117 | 0.730423 | 2.09434 | false | false | false | false |
ArchimboldiMao/remotex-iOS
|
remotex-iOS/View/AboutNode.swift
|
2
|
11116
|
//
// AboutNode.swift
// remotex-iOS
//
// Created by archimboldi on 13/05/2017.
// Copyright © 2017 me.archimboldi. All rights reserved.
//
import UIKit
import AsyncDisplayKit
class AboutNode: ASDisplayNode, ASTextNodeDelegate {
let titleNode = ASTextNode()
let sloganNode = ASTextNode()
let scrollNode = ASScrollNode()
let descriptionNode = ASTextNode()
let authorNode = ASTextNode()
let reviewNode = ASTextNode()
let linkInfoNode = ASTextNode()
let versionNode = ASTextNode()
private var aboutModel: AboutModel
init(aboutModel: AboutModel) {
self.aboutModel = aboutModel
super.init()
setupNodes()
buildNodeHierarchy()
}
func setupNodes() {
titleNode.attributedText = self.attrStringForAboutTitle(withSize: Constants.AboutLayout.TitleFontSize)
sloganNode.attributedText = self.attrStringForAboutSlogan(withSize: Constants.AboutLayout.SloganFontSize)
descriptionNode.attributedText = self.attrStringForAboutDescription(withSize: Constants.AboutLayout.DescriptionFontSize)
authorNode.attributedText = self.attrStringForAboutAuthor(withSize: Constants.AboutLayout.DescriptionFontSize)
authorNode.isUserInteractionEnabled = true
authorNode.delegate = self
reviewNode.attributedText = self.attrStringForAboutReview(withSize: Constants.AboutLayout.DescriptionFontSize)
reviewNode.isUserInteractionEnabled = true
reviewNode.delegate = self
linkInfoNode.attributedText = self.attrStringForAboutLinkInfo(withSize: Constants.AboutLayout.DescriptionFontSize)
linkInfoNode.isUserInteractionEnabled = true
linkInfoNode.delegate = self
versionNode.attributedText = self.attrStringForAboutVersion(withSize: Constants.AboutLayout.VersionFontSize)
}
func buildNodeHierarchy() {
scrollNode.addSubnode(titleNode)
scrollNode.addSubnode(sloganNode)
scrollNode.addSubnode(descriptionNode)
scrollNode.addSubnode(authorNode)
scrollNode.addSubnode(reviewNode)
scrollNode.addSubnode(linkInfoNode)
scrollNode.addSubnode(versionNode)
self.addSubnode(scrollNode)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
self.backgroundColor = Constants.TableLayout.BackgroundColor
scrollNode.automaticallyManagesSubnodes = true
scrollNode.automaticallyManagesContentSize = true
scrollNode.scrollableDirections = .down
scrollNode.view.showsVerticalScrollIndicator = false
scrollNode.layoutSpecBlock = { node, constrainedSize in
self.titleNode.style.alignSelf = .center
self.sloganNode.style.alignSelf = .center
self.sloganNode.style.spacingBefore = 8.0
self.sloganNode.style.spacingAfter = 24.0
self.descriptionNode.style.alignSelf = .start
self.authorNode.style.alignSelf = .start
self.authorNode.style.spacingBefore = 32.0
self.reviewNode.style.alignSelf = .start
self.reviewNode.style.spacingBefore = 32.0
self.reviewNode.style.spacingAfter = 32.0
self.linkInfoNode.style.alignSelf = .start
self.linkInfoNode.style.spacingAfter = 32.0
self.versionNode.style.alignSelf = .center
self.versionNode.style.spacingAfter = 8.0
let stack = ASStackLayoutSpec.vertical()
stack.children = [self.titleNode, self.sloganNode, self.descriptionNode, self.authorNode, self.reviewNode, self.linkInfoNode, self.versionNode]
return stack
}
let verticalStack = ASStackLayoutSpec.vertical()
verticalStack.children = [scrollNode]
return ASInsetLayoutSpec.init(insets: UIEdgeInsetsMake(0, 16, 0, 16), child: verticalStack)
}
private func attrStringForAboutTitle(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: size)
]
return NSAttributedString.init(string: self.aboutModel.aboutTitle, attributes: attr)
}
private func attrStringForAboutSlogan(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: size)
]
return NSAttributedString.init(string: self.aboutModel.slogan, attributes: attr)
}
private func attrStringForAboutDescription(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
return NSAttributedString.init(string: self.aboutModel.description, attributes: attr)
}
private func attrStringForAboutReview(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
let attributedString = NSMutableAttributedString.init(string: self.aboutModel.review)
attributedString.addAttributes(attr, range: NSRange.init(location: 0, length: (self.aboutModel.review as NSString).length))
attributedString.addAttributes([NSLinkAttributeName: Constants.AppStore.ReviewURL,
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.review as NSString).range(of: Constants.AppStore.TitleText))
return attributedString
}
private func attrStringForAboutAuthor(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
let attributedString = NSMutableAttributedString.init(string: self.aboutModel.author)
attributedString.addAttributes(attr, range: NSRange.init(location: 0, length: (self.aboutModel.author as NSString).length))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForCreatorGitHub(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.author as NSString).range(of: self.aboutModel.authorTwitterUsername))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForRemoteXiOSContributors(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.author as NSString).range(of: self.aboutModel.remoteXiOSContributors))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForRemoteXiOSGitHub(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.author as NSString).range(of: self.aboutModel.remoteXiOSGitHub))
return attributedString
}
private func attrStringForAboutLinkInfo(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
let attributedString = NSMutableAttributedString.init(string: self.aboutModel.linkInfo)
attributedString.addAttributes(attr, range: NSRange.init(location: 0, length: (self.aboutModel.linkInfo as NSString).length))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForRemoteXWebSite(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.linkInfo as NSString).range(of: self.aboutModel.remoteXWebSite))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForRemoteXSlack(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.linkInfo as NSString).range(of: self.aboutModel.remoteXSlack))
attributedString.addAttributes([NSLinkAttributeName: URL.URLForRemoteXEMail(),
NSForegroundColorAttributeName: UIColor.blue,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSUnderlineColorAttributeName: UIColor.clear],
range: (self.aboutModel.linkInfo as NSString).range(of: self.aboutModel.remoteXEmail))
return attributedString
}
private func attrStringForAboutVersion(withSize size: CGFloat) -> NSAttributedString {
let attr = [
NSForegroundColorAttributeName: UIColor.lightGray,
NSFontAttributeName: UIFont.systemFont(ofSize: size)
]
let versionText = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
let buildText = Bundle.main.infoDictionary?["CFBundleVersion"] as! String
return NSAttributedString.init(string: "Version \(versionText) (Build \(buildText))", attributes: attr)
}
func textNode(_ textNode: ASTextNode, shouldHighlightLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool {
return true
}
func textNode(_ textNode: ASTextNode, shouldLongPressLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool {
return true
}
func textNode(_ textNode: ASTextNode, tappedLinkAttribute attribute: String, value: Any, at point: CGPoint, textRange: NSRange) {
guard let url = value as? URL else { return }
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
|
apache-2.0
|
bf681f13beef7c82925ab57632f41d2d
| 53.753695 | 156 | 0.672964 | 5.527101 | false | false | false | false |
ancode-cn/Meizhi
|
Meizhi/Classes/business/category/CategoryTableViewController.swift
|
1
|
11319
|
//
// CategoryTableViewController.swift
// Meizhi
//
// Created by snowleft on 15/9/24.
// Copyright © 2015年 ancode. All rights reserved.
//
import UIKit
class CategoryTableViewController: UITableViewController {
private var categoryInfo:CategoryInfo?
private static let PAGE_SIZE = "20"
private var page = 0
private var list:[DataItem]?
private var estimatedCell:CategoryCell?
private var refreshType:RefreshType = RefreshType.PULL_DOWN
private var isInitialized = false
private var contentInset:UIEdgeInsets?
private weak var jumpDelegate:ViewControllerJumpDelegate?
private var mySelf:CategoryTableViewController!
private var initialize:Bool = false
func setViewControllerJumpDelegate(jumpDelegate:ViewControllerJumpDelegate?){
self.jumpDelegate = jumpDelegate
}
func setUIEdgeInsets(contentInset:UIEdgeInsets?){
self.contentInset = contentInset
}
func setCategoryInfo(categoryInfo:CategoryInfo?){
self.categoryInfo = categoryInfo
}
override func viewDidLoad() {
super.viewDidLoad()
title = categoryInfo?.title
mySelf = self
print("CategoryTableViewController=====>\(title)")
}
func initViews(){
if initialize{
return
}
initialize = true
estimatedCell = instanceEstimatedCell()
initTableView()
initMJRefresh()
}
override func viewDidAppear(animated: Bool) {
print("\(view.frame.width)===CategoryTableViewController===\(view.frame.height)")
}
override func viewWillAppear(animated: Bool) {
if !isInitialized{
}
isInitialized = true
}
private func initTableView(){
tableView.dataSource = self
tableView.delegate = self
// 设置tableView显示区域
if contentInset != nil{
tableView.contentInset = contentInset!
}else{
tableView.contentInset = UIEdgeInsetsMake(0, 0, Constant.FOOTER_HEIGHT, 0)
}
// 隐藏多余的分割线
tableView.tableFooterView = UIView()
// 注册xib
let nib = UINib(nibName: "CategoryCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "CategoryCell")
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list?.count ?? 0
}
// cell绑定数据
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath)
as! CategoryCell
configureCell(cell, indexPath: indexPath, isCalculateHeight: false)
return cell
}
private func configureCell(cell:CategoryCell,indexPath:NSIndexPath, isCalculateHeight:Bool){
if (indexPath.row % 2 == 0) {
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
} else {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark;
}
let data = list?[indexPath.row]
cell.bindData(data, indexPath: indexPath, isCalculateHeight: isCalculateHeight)
}
// 计算cell高度
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// 自动计算方式
let height = tableView.fd_heightForCellWithIdentifier("CategoryCell", cacheByIndexPath: indexPath) { (cell) -> Void in
self.configureCell(cell as! CategoryCell, indexPath: indexPath, isCalculateHeight: true)
}
print("height=============\(height)")
return height
// 手动计算方式
//let height = estimatedCellHeight(indexPath)
//return height
}
// 估算cell高度
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 67.5
}
// 处理cell line左边界不全问题
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// ios7.0+处理方式
cell.separatorInset = UIEdgeInsetsZero
// ios8.0+需附加配置
if #available(iOS 8.0, *) {
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
} else {
// Fallback on earlier versions
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 跳转详情
let data = list?[indexPath.row]
let webVC = WebViewController()
webVC.title = "详情"
webVC.setUrl(data?.url)
jumpDelegate?.jump(webVC)
}
}
// MARK: - TableViewCell处理器
extension CategoryTableViewController:TableViewCellHandler{
// 实例化用于计算的TableViewCell
func instanceEstimatedCell<CategoryCell>() -> CategoryCell?{
let cell:CategoryCell = NSBundle.mainBundle().loadNibNamed("CategoryCell", owner: nil, options: nil).last as! CategoryCell
// 不要使用以下方式,可能会造成内存泄露.
// let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell") as! CategoryCell
return cell
}
// 计算cell高度
func estimatedCellHeight(indexPath: NSIndexPath) -> CGFloat{
var height:CGFloat?
if let categoryItem = list?[indexPath.row]{
height = categoryItem.cellHeight
if height != nil{
return height ?? 0
}
estimatedCell?.bindData(categoryItem, indexPath: indexPath, isCalculateHeight: true)
height = estimatedCell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
// height = CGRectGetMaxY(estimatedCell!.lb_who.frame) + 10
categoryItem.cellHeight = height
print("\(indexPath.row)======\(height)")
}
return height ?? 0
}
}
// MARK: - 下拉刷新
extension CategoryTableViewController{
private func initMJRefresh(){
weak var weakSelf:CategoryTableViewController? = mySelf
tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
weakSelf?.refreshType = RefreshType.PULL_DOWN
weakSelf?.page = 1
weakSelf?.loadData()
})
let footer:MJRefreshAutoNormalFooter = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
weakSelf?.refreshType = RefreshType.LOAD_MORE
weakSelf?.loadData()
})
footer.automaticallyRefresh = true
tableView.footer = footer
tableView.header.beginRefreshing()
}
// 停止刷新
private func endRefreshing(){
if refreshType == RefreshType.PULL_DOWN{
tableView.header.endRefreshing()
}else{
tableView.footer.endRefreshing()
}
}
}
// MARK: - 数据处理
extension CategoryTableViewController{
// 从网络/本地加载数据
private func loadData(){
if categoryInfo == nil || categoryInfo?.url == nil{
endRefreshing()
return
}
let requestUrl:String = categoryInfo!.url + CategoryTableViewController.PAGE_SIZE + "/" + String(page)
let url:String? = requestUrl.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
print(url)
if url == nil{
endRefreshing()
return
}
// 网络监测
AFNetworkReachabilityManager.sharedManager().startMonitoring()
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in
print("network status=====>\(status)")
}
// 网络请求
weak var weakSelf = self // 弱引用self指针
let manager = AFHTTPRequestOperationManager()
//使用这个将得到的是NSData
manager.responseSerializer = AFHTTPResponseSerializer()
//使用这个将得到的是JSON
// manager.responseSerializer = AFJSONResponseSerializer()
manager.GET(url, parameters: nil, success: { (operation:AFHTTPRequestOperation?, responseObject:AnyObject?) -> Void in
print("responseObject type=====>\(responseObject?.classForCoder)")
if responseObject != nil && responseObject is NSData{
weakSelf?.handleResponse(operation?.response, data: responseObject as? NSData)
}else{
weakSelf?.endRefreshing()
}
}) { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
weakSelf?.endRefreshing()
}
}
/**
处理服务器接口响应
- parameter response: NSHTTPURLResponse
- parameter data: 源数据
*/
private func handleResponse(response:NSHTTPURLResponse?, data:NSData?){
if response?.statusCode == 200 && data != nil{
if let list:[DataItem] = parseJson(data!){
if refreshType == RefreshType.PULL_DOWN{
self.list = list
}else{
if self.list == nil{
self.list = [DataItem]()
}
self.list? += list
}
print("tableView.reloadData=====>\(list.count)")
tableView.reloadData()
page += 1
}else{
// no data.
if refreshType == RefreshType.LOAD_MORE{
tableView.footer.noticeNoMoreData()
}
}
}
endRefreshing()
}
/**
解析json数据
- parameter data: 源数据
- returns: [CategoryItem]
*/
private func parseJson(data:NSData) -> [DataItem]?{
var list:[DataItem]? = nil
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
let error = json["error"] as? Bool
if error != nil && error == false{
if let results = json["results"] as? Array<AnyObject>{
list = [DataItem]()
for(var i=0; i < results.count; i++){
if let dic = results[i] as? NSDictionary{
let item = DataItem(fromDictionary: dic)
// test
if i > 0{
item.desc! += list![i - 1].desc
item.desc! += "abcdefghijklmnopqrstuvwxyz"
}
list?.append(item)
}
}
}
}
} catch {
print("parse json error!")
}
return list
}
}
|
mit
|
2f0171de08db1b2890415fa900add9ec
| 32.37386 | 136 | 0.588707 | 5.441031 | false | false | false | false |
zyhndesign/SDX_DG
|
sdxdg/sdxdg/ShareViewController.swift
|
1
|
4449
|
//
// ShareViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/30.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
class ShareViewController : UIViewController,UIWebViewDelegate{
@IBOutlet var webView: UIWebView!
var hud:MBProgressHUD?
@IBOutlet var sendSareBtn: UIButton!
var matchId:Int = 0
private var shareUrl:String!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
//let filePath:String = Bundle.main.path(forResource: "nDetail", ofType: "html",inDirectory:"sdxdp")!
//let url:URL = URL.init(fileURLWithPath: filePath)
shareUrl = ConstantsUtil.APP_DGGL_SHARE_DETAIL + "\(matchId)"
let url:URL = URL.init(string: shareUrl)!
let request:URLRequest = URLRequest.init(url: url)
webView.loadRequest(request)
hud = MBProgressHUD.showAdded(to: self.view, animated: true)
self.navigationItem.hidesBackButton = true
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "backBtn"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(shareButtonClicked(sender:)))
self.navigationItem.leftItemsSupplementBackButton = true
}
func webViewDidStartLoad(_ webView: UIWebView) {
hud?.label.text = "加载中..."
}
func webViewDidFinishLoad(_ webView: UIWebView) {
hud?.hide(animated: true)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
}
@IBAction func sendSareBtnClick(_ sender: Any) {
hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud?.label.text = "加载中..."
let result:String = self.webView.stringByEvaluatingJavaScript(from: "uploadShareContent()")!
if(result.isEmpty){
hud?.label.text = "分享数据提交失败!"
hud?.hide(animated: true, afterDelay: 2.0)
}
else{
hud?.hide(animated: true)
let array = result.components(separatedBy: "|")
let code = array[0];
UMSocialUIManager.showShareMenuViewInWindow{ (platformType,userInfo) -> Void in
let messageObject:UMSocialMessageObject = UMSocialMessageObject.init()
messageObject.text = ""//分享的文本
let shareObject:UMShareWebpageObject = UMShareWebpageObject.init()
shareObject.title = array[1]
shareObject.descr = array[2]
shareObject.thumbImage = UIImage.init(named: "AppIcon")//缩略图
shareObject.webpageUrl = ConstantsUtil.APP_DGGL_SHARE_RESULT_DETAIL + "\(code)";
messageObject.shareObject = shareObject;
UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self, completion: { (shareResponse, error) -> Void in
if error != nil {
print("Share Fail with error :%@", error)
}else{
let parameters:Parameters = ["matchId":self.matchId,"shareStatus":1];
Alamofire.request(ConstantsUtil.APP_USER_LOGIN_URL,method:.post,parameters:parameters).responseJSON{
response in
switch response.result{
case .success:
MessageUtil.showMessage(view: self.view, message: "分享成功!")
case .failure(let error):
MessageUtil.showMessage(view: self.view, message: error.localizedDescription)
}
}
}
})
}
}
}
/**
分享按钮响应事件
*/
func shareButtonClicked(sender:UIButton) {
if (self.webView.canGoBack){
self.webView.goBack();
}
else{
self.navigationController?.popViewController(animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
178d9a92907df19bdfd02bd4482cd8e8
| 36.401709 | 204 | 0.572212 | 5.118129 | false | false | false | false |
SwiftTools/Switt
|
Switt/Source/Utility/Public/NonemptyArray.swift
|
1
|
736
|
public struct NonemptyArray<T> {
public var first: T {
didSet {
array = [first] + latter
}
}
public var latter: [T] {
didSet {
array = [first] + latter
}
}
public private(set) var array: [T]
public init(first: T, latter: [T] = []) {
self.first = first
self.latter = latter
self.array = [first] + latter
}
public init?(array: [T]) {
if let first = array.first {
self.first = first
self.latter = array.dropFirst().map { $0 }
self.array = array
} else {
return nil
}
}
public var count: Int {
return array.count
}
}
|
mit
|
92318ec787929a3da99ca4b1be3c85cc
| 20.676471 | 54 | 0.45788 | 4.066298 | false | false | false | false |
lsonlee/Swift_MVVM
|
Swift_Project/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineSpinFadeLoader.swift
|
2
|
3950
|
//
// NVActivityIndicatorAnimationLineSpinFadeLoader.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationLineSpinFadeLoader: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSpacing: CGFloat = 2
let lineSize = CGSize(width: (size.width - 4 * lineSpacing) / 5, height: (size.height - 2 * lineSpacing) / 3)
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 1.2
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw lines
for i in 0 ..< 8 {
let line = lineAt(angle: CGFloat.pi / 4.0 * CGFloat(i),
size: lineSize,
origin: CGPoint(x: x, y: y),
containerSize: size,
color: color)
animation.beginTime = beginTime + beginTimes[i]
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
func lineAt(angle: CGFloat, size: CGSize, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer {
let radius = containerSize.width / 2 - max(size.width, size.height) / 2
let lineContainerSize = CGSize(width: max(size.width, size.height), height: max(size.width, size.height))
let lineContainer = CALayer()
let lineContainerFrame = CGRect(
x: origin.x + radius * (cos(angle) + 1),
y: origin.y + radius * (sin(angle) + 1),
width: lineContainerSize.width,
height: lineContainerSize.height)
let line = NVActivityIndicatorShape.line.layerWith(size: size, color: color)
let lineFrame = CGRect(
x: (lineContainerSize.width - size.width) / 2,
y: (lineContainerSize.height - size.height) / 2,
width: size.width,
height: size.height)
lineContainer.frame = lineContainerFrame
line.frame = lineFrame
lineContainer.addSublayer(line)
lineContainer.sublayerTransform = CATransform3DMakeRotation(CGFloat.pi / 2.0 + angle, 0, 0, 1)
return lineContainer
}
}
|
mit
|
dc54c874623e9ef0c25f6a4d7158e237
| 43.382022 | 117 | 0.656709 | 4.561201 | false | false | false | false |
pkx0128/UIKit
|
MTabBarAndNavigation/MTabBarAndNavigation/Class/Main/MainViewController.swift
|
1
|
2493
|
//
// MainViewController.swift
// MTabBarAndNavigation
//
// Created by pankx on 2017/10/1.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setupChildView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MainViewController {
/// 通过传入数组
///let tabArr = [["className":"HomeViewController","title"]:"首页","image":"tabbar_home","selectedImage":"tabbar_home_selected"]]
/// - Parameter dit: 传入的数组
/// - Returns: 返回一个View
func control(dit:[String:String]) -> UIViewController {
guard let className = dit["className"], let title = dit["title"], let image = dit["image"],
let selectedImage = dit["selectedImage"] else {
return UIViewController()
}
//获取命名空间
let cln = (Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "") + "." + className
//使用反射机制通过类名获取具体的类
let nv = NSClassFromString(cln) as! BaseViewController.Type
let vc = nv.init()
vc.title = title
vc.tabBarItem.image = UIImage(named: image)
vc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.withRenderingMode(.alwaysOriginal)
vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.orange], for: .selected)
let nav = NavViewController(rootViewController: vc)
return nav
}
/// 创建子控制器
func setupChildView() {
let tabArr = [["className":"HomeViewController","title":"首页","image":"tabbar_home","selectedImage":"tabbar_home_selected"],
["className":"MessageViewController","title":"信息","image":"tabbar_message_center","selectedImage":"tabbar_message_center_selected"],
["className":"DiscoverViewController","title":"发现","image":"tabbar_discover","selectedImage":"tabbar_discover_selected"],
["className":"ProfileViewController","title":"我","image":"tabbar_profile","selectedImage":"tabbar_profile_selected"]]
var ArrC = [UIViewController]()
for nav in tabArr {
ArrC.append(control(dit: nav))
}
viewControllers = ArrC
}
}
|
mit
|
8fa0669496f805c7e22d687598b1ef26
| 36.873016 | 154 | 0.633277 | 4.800805 | false | false | false | false |
Stitch7/mclient
|
mclient/PrivateMessages/_MessageKit/Views/MessagesCollectionView.swift
|
1
|
7188
|
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
open class MessagesCollectionView: UICollectionView {
// MARK: - Properties
open weak var messagesDataSource: MessagesDataSource?
open weak var messagesDisplayDelegate: MessagesDisplayDelegate?
open weak var messagesLayoutDelegate: MessagesLayoutDelegate?
open weak var messageCellDelegate: MessageCellDelegate?
private var indexPathForLastItem: IndexPath? {
let lastSection = numberOfSections - 1
guard lastSection >= 0, numberOfItems(inSection: lastSection) > 0 else { return nil }
return IndexPath(item: numberOfItems(inSection: lastSection) - 1, section: lastSection)
}
// MARK: - Initializers
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
backgroundColor = .white
registerReusableViews()
setupGestureRecognizers()
}
required public init?(coder aDecoder: NSCoder) {
super.init(frame: .zero, collectionViewLayout: MessagesCollectionViewFlowLayout())
}
public convenience init() {
self.init(frame: .zero, collectionViewLayout: MessagesCollectionViewFlowLayout())
}
// MARK: - Methods
private func registerReusableViews() {
register(TextMessageCell.self)
register(MediaMessageCell.self)
register(LocationMessageCell.self)
register(MessageReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader)
register(MessageReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter)
}
private func setupGestureRecognizers() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
tapGesture.delaysTouchesBegan = true
addGestureRecognizer(tapGesture)
}
@objc
open func handleTapGesture(_ gesture: UIGestureRecognizer) {
guard gesture.state == .ended else { return }
let touchLocation = gesture.location(in: self)
guard let indexPath = indexPathForItem(at: touchLocation) else { return }
let cell = cellForItem(at: indexPath) as? MessageContentCell
cell?.handleTapGesture(gesture)
}
public func scrollToBottom(animated: Bool = false) {
let collectionViewContentHeight = collectionViewLayout.collectionViewContentSize.height
performBatchUpdates(nil) { _ in
self.scrollRectToVisible(CGRect(0.0, collectionViewContentHeight - 1.0, 1.0, 1.0), animated: animated)
}
}
public func reloadDataAndKeepOffset() {
// stop scrolling
setContentOffset(contentOffset, animated: false)
// calculate the offset and reloadData
let beforeContentSize = contentSize
reloadData()
layoutIfNeeded()
let afterContentSize = contentSize
// reset the contentOffset after data is updated
let newOffset = CGPoint(
x: contentOffset.x + (afterContentSize.width - beforeContentSize.width),
y: contentOffset.y + (afterContentSize.height - beforeContentSize.height))
setContentOffset(newOffset, animated: false)
}
/// Registers a particular cell using its reuse-identifier
public func register<T: UICollectionViewCell>(_ cellClass: T.Type) {
register(cellClass, forCellWithReuseIdentifier: String(describing: T.self))
}
/// Registers a reusable view for a specific SectionKind
public func register<T: UICollectionReusableView>(_ headerFooterClass: T.Type, forSupplementaryViewOfKind kind: String) {
register(headerFooterClass,
forSupplementaryViewOfKind: kind,
withReuseIdentifier: String(describing: T.self))
}
/// Registers a nib with reusable view for a specific SectionKind
public func register<T: UICollectionReusableView>(_ nib: UINib? = UINib(nibName: String(describing: T.self), bundle: nil), headerFooterClassOfNib headerFooterClass: T.Type, forSupplementaryViewOfKind kind: String) {
register(nib,
forSupplementaryViewOfKind: kind,
withReuseIdentifier: String(describing: T.self))
}
/// Generically dequeues a cell of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
public func dequeueReusableCell<T: UICollectionViewCell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else {
fatalError("Unable to dequeue \(String(describing: cellClass)) with reuseId of \(String(describing: T.self))")
}
return cell
}
/// Generically dequeues a header of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
public func dequeueReusableHeaderView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T {
let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: String(describing: T.self), for: indexPath)
guard let viewType = view as? T else {
fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))")
}
return viewType
}
/// Generically dequeues a footer of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
public func dequeueReusableFooterView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T {
let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: String(describing: T.self), for: indexPath)
guard let viewType = view as? T else {
fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))")
}
return viewType
}
}
|
mit
|
c5d5e52852687c0ddde2d4c818e077a4
| 44.207547 | 219 | 0.714524 | 5.38024 | false | false | false | false |
alitaso345/swift-annict-client
|
AnnictAPIClient/User.swift
|
1
|
2343
|
struct User :JSONDecodable {
let id: Int
let username: String
let name: String
let description: String
let url: String?
let avatarURL: String
let backgroundImageURL: String
let recordsCount: Int
let createdAt: String
init(json: Any) throws {
guard let dictionary = json as? [String: Any] else {
throw JSONDecodeError.invalidFormat(json: json)
}
guard let id = dictionary["id"] as? Int else {
throw JSONDecodeError.missingValue(key: "id", actualValue: dictionary["id"])
}
guard let username = dictionary["username"] as? String else {
throw JSONDecodeError.missingValue(key: "username", actualValue: dictionary["username"])
}
guard let name = dictionary["name"] as? String else {
throw JSONDecodeError.missingValue(key: "name", actualValue: dictionary["name"])
}
guard let description = dictionary["description"] as? String else {
throw JSONDecodeError.missingValue(key: "description", actualValue: dictionary["description"])
}
if let url = dictionary["user"] as? String {
self.url = url
} else {
self.url = nil
}
guard let avatarURL = dictionary["avatar_url"] as? String else {
throw JSONDecodeError.missingValue(key: "avatar_url", actualValue: dictionary["avatar_url"])
}
guard let backgroundImageURL = dictionary["background_image_url"] as? String else {
throw JSONDecodeError.missingValue(key: "background_image_url", actualValue: dictionary["background_image_url"])
}
guard let recordsCount = dictionary["records_count"] as? Int else {
throw JSONDecodeError.missingValue(key: "records_count", actualValue: dictionary["records_count"])
}
guard let createdAt = dictionary["created_at"] as? String else {
throw JSONDecodeError.missingValue(key: "created_at", actualValue: dictionary["created_at"])
}
self.id = id
self.username = username
self.name = name
self.description = description
self.avatarURL = avatarURL
self.backgroundImageURL = backgroundImageURL
self.recordsCount = recordsCount
self.createdAt = createdAt
}
}
|
mit
|
26c52be42f43780e7a8f62cbd3836e98
| 35.609375 | 124 | 0.629535 | 4.922269 | false | false | false | false |
samodom/TestableUIKit
|
TestableUIKit/UIResponder/UIViewController/UIViewControllerTransitionIndirectSpy.swift
|
1
|
9331
|
//
// UIViewControllerTransitionIndirectSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/25/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import TestSwagger
import FoundationSwagger
public extension UIViewController {
private static let superclassTransitionCalledString = UUIDKeyString()
private static let superclassTransitionCalledKey =
ObjectAssociationKey(superclassTransitionCalledString)
private static let superclassTransitionCalledReference =
SpyEvidenceReference(key: superclassTransitionCalledKey)
private static let superclassTransitionFromControllerString = UUIDKeyString()
private static let superclassTransitionFromControllerKey =
ObjectAssociationKey(superclassTransitionFromControllerString)
private static let superclassTransitionFromControllerReference =
SpyEvidenceReference(key: superclassTransitionFromControllerKey)
private static let superclassTransitionToControllerString = UUIDKeyString()
private static let superclassTransitionToControllerKey =
ObjectAssociationKey(superclassTransitionToControllerString)
private static let superclassTransitionToControllerReference =
SpyEvidenceReference(key: superclassTransitionToControllerKey)
private static let superclassTransitionDurationString = UUIDKeyString()
private static let superclassTransitionDurationKey =
ObjectAssociationKey(superclassTransitionDurationString)
private static let superclassTransitionDurationReference =
SpyEvidenceReference(key: superclassTransitionDurationKey)
private static let superclassTransitionOptionsString = UUIDKeyString()
private static let superclassTransitionOptionsKey =
ObjectAssociationKey(superclassTransitionOptionsString)
private static let superclassTransitionOptionsReference =
SpyEvidenceReference(key: superclassTransitionOptionsKey)
private static let superclassTransitionAnimationsString = UUIDKeyString()
private static let superclassTransitionAnimationsKey =
ObjectAssociationKey(superclassTransitionAnimationsString)
private static let superclassTransitionAnimationsReference =
SpyEvidenceReference(key: superclassTransitionAnimationsKey)
private static let superclassTransitionCompletionString = UUIDKeyString()
private static let superclassTransitionCompletionKey =
ObjectAssociationKey(superclassTransitionCompletionString)
private static let superclassTransitionCompletionReference =
SpyEvidenceReference(key: superclassTransitionCompletionKey)
/// Spy controller for ensuring a controller has called its superclass's
/// implementation of `transition(from:to:duration:options:animations:completion:)`.
public enum TransitionIndirectSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UIViewController.self
public static let vector = SpyVector.indirect
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(UIViewController.transition(from:to:duration:options:animations:completion:)),
spy: #selector(UIViewController.indirectspy_transition(from:to:duration:options:animations:completion:))
)
] as Set
public static let evidence = [
superclassTransitionCalledReference,
superclassTransitionFromControllerReference,
superclassTransitionToControllerReference,
superclassTransitionDurationReference,
superclassTransitionOptionsReference,
superclassTransitionAnimationsReference,
superclassTransitionCompletionReference
] as Set
public static var forwardsInvocations = true
}
/// Spy method that replaces the true implementation of
/// `transition(from:to:duration:options:animations:completion:)`
public func indirectspy_transition(
from sourceController: UIViewController,
to destinationController: UIViewController,
duration: TimeInterval,
options: UIViewAnimationOptions,
animations: (() -> Void)?,
completion: ((Bool) -> Void)?
) {
superclassTransitionCalled = true
superclassTransitionFromController = sourceController
superclassTransitionToController = destinationController
superclassTransitionDuration = duration
superclassTransitionOptions = options
if UIViewController.TransitionIndirectSpyController.forwardsInvocations {
indirectspy_transition(
from: sourceController,
to: destinationController,
duration: duration,
options: options,
animations: animations,
completion: completion
)
}
else {
superclassTransitionAnimations = animations
superclassTransitionCompletion = completion
}
}
/// Indicates whether the `transition(from:to:duration:options:animations:completion:)`
/// method has been called on this object's superclass.
public final var superclassTransitionCalled: Bool {
get {
return loadEvidence(with: UIViewController.superclassTransitionCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UIViewController.superclassTransitionCalledReference)
}
}
/// Provides the source controller passed to
/// `transition(from:to:duration:options:animations:completion:)` if called.
public final var superclassTransitionFromController: UIViewController? {
get {
return loadEvidence(with: UIViewController.superclassTransitionFromControllerReference) as? UIViewController
}
set {
let reference = UIViewController.superclassTransitionFromControllerReference
guard let source = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(source, with: reference)
}
}
/// Provides the destination controller passed to
/// `transition(from:to:duration:options:animations:completion:)` if called.
public final var superclassTransitionToController: UIViewController? {
get {
return loadEvidence(with: UIViewController.superclassTransitionToControllerReference) as? UIViewController
}
set {
let reference = UIViewController.superclassTransitionToControllerReference
guard let destination = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(destination, with: reference)
}
}
/// Provides the duration passed to
/// `transition(from:to:duration:options:animations:completion:)` if called.
public final var superclassTransitionDuration: TimeInterval? {
get {
return loadEvidence(with: UIViewController.superclassTransitionDurationReference) as? TimeInterval
}
set {
let reference = UIViewController.superclassTransitionDurationReference
guard let duration = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(duration, with: reference)
}
}
/// Provides the options passed to `transition(from:to:duration:options:animations:completion:)`
/// if called.
public final var superclassTransitionOptions: UIViewAnimationOptions? {
get {
return loadEvidence(with: UIViewController.superclassTransitionOptionsReference) as? UIViewAnimationOptions
}
set {
let reference = UIViewController.superclassTransitionOptionsReference
guard let options = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(options, with: reference)
}
}
/// Provides the animations closure passed to
/// `transition(from:to:duration:options:animations:completion:)` if called.
public final var superclassTransitionAnimations: UIViewAnimations? {
get {
return loadEvidence(with: UIViewController.superclassTransitionAnimationsReference) as? UIViewAnimations
}
set {
let reference = UIViewController.superclassTransitionAnimationsReference
guard let animations = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(animations, with: reference)
}
}
/// Provides the completion handler passed to
/// `transition(from:to:duration:options:animations:completion:)` if called.
public final var superclassTransitionCompletion: UIViewAnimationsCompletion? {
get {
return loadEvidence(with: UIViewController.superclassTransitionCompletionReference) as? UIViewAnimationsCompletion
}
set {
let reference = UIViewController.superclassTransitionCompletionReference
guard let completion = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(completion, with: reference)
}
}
}
|
mit
|
db61acb71badff79882f8595c41537f3
| 39.742358 | 126 | 0.70761 | 6.57969 | false | false | false | false |
mono0926/LicensePlist
|
Sources/LicensePlistCore/Entity/CocoaPodsLicense.swift
|
1
|
2201
|
import Foundation
import LoggerAPI
public struct CocoaPodsLicense: License, Equatable {
public let library: CocoaPods
public let body: String
public static func==(lhs: CocoaPodsLicense, rhs: CocoaPodsLicense) -> Bool {
return lhs.library == rhs.library &&
lhs.body == rhs.body
}
}
extension CocoaPodsLicense: CustomStringConvertible {
public var description: String {
return "name: \(library.name), nameSpecified: \(nameSpecified ?? "")\nbody: \(String(body.prefix(20)))…\nversion: \(version ?? "")"
}
}
extension CocoaPodsLicense {
public static func load(_ content: String, versionInfo: VersionInfo, config: Config) -> [CocoaPodsLicense] {
do {
let plistData = content.data(using: .utf8)!
let plistDecoder = PropertyListDecoder()
return try plistDecoder.decode(AcknowledgementsPlist.self, from: plistData).preferenceSpecifiers
.filter { $0.isLicense }
.map {
let name = $0.title
return CocoaPodsLicense(library: CocoaPods(name: name,
nameSpecified: config.renames[name],
version: versionInfo.version(name: $0.title),
licenseType: LicenseType(id: $0.license)),
body: $0.footerText)
}
} catch let e {
Log.error(String(describing: e))
return []
}
}
}
private struct AcknowledgementsPlist: Decodable {
enum CodingKeys: String, CodingKey {
case preferenceSpecifiers = "PreferenceSpecifiers"
}
let preferenceSpecifiers: [PreferenceSpecifier]
}
private struct PreferenceSpecifier: Decodable {
enum CodingKeys: String, CodingKey {
case footerText = "FooterText"
case title = "Title"
case type = "Type"
case license = "License"
}
let footerText: String
let title: String
let type: String
let license: String?
var isLicense: Bool { return license != nil }
}
|
mit
|
850afb36afc122554a667d9ad2be0707
| 33.904762 | 139 | 0.571623 | 5.113953 | false | false | false | false |
skyfe79/RxPlayground
|
RxToDoList-MVVM/Pods/RxCocoa/RxCocoa/Common/Observables/NSObject+Rx.swift
|
23
|
8401
|
//
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if !DISABLE_SWIZZLING
var deallocatingSubjectTriggerContext: UInt8 = 0
var deallocatingSubjectContext: UInt8 = 0
#endif
var deallocatedSubjectTriggerContext: UInt8 = 0
var deallocatedSubjectContext: UInt8 = 0
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`rx_observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `rx_observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_observe<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial], retainSelf: Bool = true) -> Observable<E?> {
return KVOObservable(object: self, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
}
#if !DISABLE_SWIZZLING
// KVO
extension NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `rx_observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_observeWeakly<E>(type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.New, .Initial]) -> Observable<E?> {
return observeWeaklyKeyPathFor(self, keyPath: keyPath, options: options)
.map { n in
return n as? E
}
}
}
#endif
// Dealloc
extension NSObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var rx_deallocated: Observable<Void> {
return rx_synchronized {
if let deallocObservable = objc_getAssociatedObject(self, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable._subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(self, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable._subject
}
}
#if !DISABLE_SWIZZLING
/**
Observable sequence of message arguments that completes when object is deallocated.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of object deallocating events.
*/
public func rx_sentMessage(selector: Selector) -> Observable<[AnyObject]> {
return rx_synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return rx_deallocating.map { _ in [] }
}
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: MessageSentObservable
if let existingSubject = objc_getAssociatedObject(self, selectorReference) as? MessageSentObservable {
subject = existingSubject
}
else {
subject = MessageSentObservable()
objc_setAssociatedObject(
self,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject.asObservable()
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self, selector, &error)
if targetImplementation == nil {
return Observable.error(error?.rxCocoaErrorForTarget(self) ?? RxCocoaError.Unknown)
}
subject.targetImplementation = targetImplementation
return subject.asObservable()
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var rx_deallocating: Observable<()> {
return rx_synchronized {
let subject: DeallocatingObservable
if let existingSubject = objc_getAssociatedObject(self, rxDeallocatingSelectorReference) as? DeallocatingObservable {
subject = existingSubject
}
else {
subject = DeallocatingObservable()
objc_setAssociatedObject(
self,
rxDeallocatingSelectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject.asObservable()
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self, deallocSelector, &error)
if targetImplementation == nil {
return Observable.error(error?.rxCocoaErrorForTarget(self) ?? RxCocoaError.Unknown)
}
subject.targetImplementation = targetImplementation
return subject.asObservable()
}
}
#endif
}
let deallocSelector = "dealloc" as Selector
let rxDeallocatingSelector = RX_selector("dealloc")
let rxDeallocatingSelectorReference = RX_reference_from_selector(rxDeallocatingSelector)
extension NSObject {
func rx_synchronized<T>(@noescape action: () -> T) -> T {
objc_sync_enter(self)
let result = action()
objc_sync_exit(self)
return result
}
}
|
mit
|
ce9d00062ca8db723ffaf3b7b70d0eb6
| 36.837838 | 163 | 0.666548 | 5.090909 | false | false | false | false |
nathawes/swift
|
test/api-digester/Inputs/cake.swift
|
6
|
2838
|
@_exported import cake
public protocol P1 {}
public protocol P2 {}
public protocol P3: P2, P1 {}
@frozen
public struct S1: P1 {
public static func foo1() {}
mutating public func foo2() {}
internal func foo3() {}
private func foo4() {}
fileprivate func foo5() {}
public func foo6() -> Void {}
}
extension S1: P2 {}
public class C0<T1, T2, T3> {}
public typealias C0Alias = C0<S1, S1, S1>
public class C1: C0Alias {
open class func foo1() {}
public weak var Ins : C1?
public unowned var Ins2 : C1 = C1()
}
public extension C0 where T1 == S1, T2 == S1, T3 == S1 {
func conditionalFooExt() {}
}
public extension C0 {
func unconditionalFooExt() {}
}
public func foo1(_ a: Int = 1, b: S1) {}
public func foo2(_ a: Int = #line, b: S1) {}
public enum Number: Int {
case one
}
public func foo3(_ a: [Int: String]) {}
public extension Int {
public func foo() {}
}
@frozen
public struct fixedLayoutStruct {
public var a = 1
private var b = 2 { didSet {} willSet(value) {} }
var c = 3
@available(*, unavailable)
public let unavailableProperty = 1
}
extension Int: P1 { public func bar() {} }
public protocol ProWithAssociatedType {
associatedtype A
associatedtype B = Int
}
public protocol SubsContainer {
subscript(getter i: Int) -> Int { get }
subscript(setter i: Int) -> Int { get set }
}
public extension ProWithAssociatedType {
func NonReqFunc() {}
var NonReqVar: Int { return 1 }
typealias NonReqAlias = Int
}
public protocol PSuper {
associatedtype T
func foo()
}
public protocol PSub: PSuper {
associatedtype T
func foo()
}
public let GlobalVar = 1
public extension P1 {
static func +(lhs: P1, rhs: P1) -> P1 { return lhs }
}
infix operator ..*..
@usableFromInline
@_fixed_layout
class UsableFromInlineClass {
private var Prop = 1
}
class InternalType {}
extension InternalType {}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public extension PSuper {
func futureFoo() {}
}
public class FutureContainer {
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func futureFoo() {}
@available(macOS 10.15, *)
public func NotfutureFoo() {}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension FutureContainer: P1 {}
extension FutureContainer: P2 {}
@available(macOS 10.1, iOS 10.2, tvOS 10.3, watchOS 3.4, *)
public class PlatformIntroClass {}
@available(swift, introduced: 5)
public class SwiftIntroClass {}
@objc(NewObjCClass)
public class SwiftObjcClass {
@objc(ObjCFool:ObjCA:ObjCB:)
public func foo(a:Int, b:Int, c: Int) {}
}
@available(iOS 10.2, tvOS 10.3, watchOS 3.4, *)
@available(macOS, unavailable)
public class UnavailableOnMac {}
@available(macOS, unavailable)
extension SwiftObjcClass {
public func functionUnavailableOnMac() {}
}
@_alwaysEmitIntoClient
public func emitIntoClientFunc() {}
|
apache-2.0
|
4e40a49713d50116f52c155d73900ab0
| 18.708333 | 59 | 0.684285 | 3.225 | false | false | false | false |
nathawes/swift
|
test/attr/attr_objc.swift
|
4
|
97055
|
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.ast
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainStruct { } // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}}
class FáncyName {}
@objc (FancyName) extension FáncyName {}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_globalVar: Int
var subject_getterSetter: Int {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
get {
return 0
}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
set {
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
willSet {
}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
didSet {
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}}
willSet {
}
@objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}}
didSet {
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}}
func subject_freeFunc() {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_localVar: Int
// expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_nestedFreeFunc() {
}
}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}}
func subject_genericFunc<T>(t: T) {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_localVar: Int
// expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_instanceVar: Int
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_instanceVar: Int
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{extensions of generic classes cannot contain '@objc' members}}
@objc func extFoo() {} // expected-error{{extensions of generic classes cannot contain '@objc' members}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3) // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-31=}}
case subject_enumElement3, subject_enumElement4
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}}
case subject_enumElement7
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
enum subject_enum2 {
@objc(subject_enum2Element1) // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-32=}}
case subject_enumElement1
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_instanceVar: Int { get }
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
func subject_instanceFunc()
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
static func subject_staticFunc()
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func inoutFunc(a: inout Int) {}
// expected-error@-1{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // okay
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // okay
}
@objc(CustomNameForSubclassOfGeneric) // okay
class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric3 {
@objc func foo() {} // okay
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid1 {
@objc class subscript(_ i: Int) -> AnyObject? {
// expected-error@-1 {{class subscript cannot be marked @objc}}
return nil
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_propertyInvalid1 {
@objc
let plainStruct = PlainStruct() // expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @_hasStorage @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get {
// CHECK-NEXT: return
// CHECK-NEXT: }
didSet {}
// CHECK-NEXT: {{^}} @objc set {
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get {
// CHECK-NEXT: return
// CHECK-NEXT: }
didSet {}
// CHECK-NEXT: {{^}} @objc set {
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: Unicode.Scalar
// CHECK-LABEL: @objc var var_Char: Unicode.Scalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Unconstrained_() -> GP_Unconstrained {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc @_hasInitialValue var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc @_hasInitialValue class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}@_inheritsConvenienceInitializers class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}}
@IBSegueAction func myAction(coder: Undeclared, sender: Undeclared) -> Undeclared {fatalError()} // expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @objc @IBOutlet @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}}
// expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}}
// expected-note@-4 {{add '!' to form an implicitly unwrapped optional}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @objc @IBAction func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @IBSegueAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBSegueAction {
class HasIBSegueAction {
@IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject {fatalError()}
// CHECK: {{^}} @objc @IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject {
@IBSegueAction func badSegueAction(_ coder: PlainStruct?) -> Int? {fatalError()}
// expected-error@-1{{method cannot be marked @IBSegueAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @IBInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBInspectable {
class HasIBInspectable {
@IBInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @GKInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasGKInspectable {
class HasGKInspectable {
@GKInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 {
// CHECK-NEXT: {{^}} @objc get
// CHECK-NEXT: {{^}} @objc set
// CHECK-NEXT: {{^}} }
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @NSManaged dynamic var badManaged: PlainStruct {
// CHECK-NEXT: {{^}} get
// CHECK-NEXT: {{^}} set
// CHECK-NEXT: {{^}} }
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}}
deinit { }
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc extension PlainClass {
// CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) {
final func objc_ext_objc_okay(_: Int) { }
final func objc_ext_objc_not_okay(_: PlainStruct) { }
// expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) {
@nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { }
}
@objc class ObjC_Class1 : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc class NeverReturningMethod {
@objc func doesNotReturn() -> Never {}
}
// SR-5025
class User: NSObject {
}
@objc extension User {
var name: String {
get {
return "No name"
}
set {
// Nothing
}
}
var other: String {
unsafeAddress { // expected-error{{addressors are not allowed to be marked @objc}}
}
}
}
// 'dynamic' methods cannot be @inlinable.
class BadClass {
@inlinable @objc dynamic func badMethod1() {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}}
}
@objc
protocol ObjCProtocolWithWeakProperty {
weak var weakProp: AnyObject? { get set } // okay
}
@objc
protocol ObjCProtocolWithUnownedProperty {
unowned var unownedProp: AnyObject { get set } // okay
}
// rdar://problem/46699152: errors about read/modify accessors being implicitly
// marked @objc.
@objc class MyObjCClass: NSObject {}
@objc
extension MyObjCClass {
@objc
static var objCVarInObjCExtension: Bool {
get {
return true
}
set {}
}
// CHECK: {{^}} @objc private dynamic func stillExposedToObjCDespiteBeingPrivate()
private func stillExposedToObjCDespiteBeingPrivate() {}
}
@objc private extension MyObjCClass {
// CHECK: {{^}} @objc dynamic func alsoExposedToObjCDespiteBeingPrivate()
func alsoExposedToObjCDespiteBeingPrivate() {}
}
@objcMembers class VeryObjCClass: NSObject {
// CHECK: {{^}} private func notExposedToObjC()
private func notExposedToObjC() {}
}
// SR-9035
class SR_9035_C {}
@objc protocol SR_9035_P {
func throwingMethod1() throws -> Unmanaged<CFArray> // Ok
func throwingMethod2() throws -> Unmanaged<SR_9035_C> // expected-error {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-1 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
// SR-12801: Make sure we reject an @objc generic subscript.
class SR12801 {
@objc subscript<T>(foo : [T]) -> Int { return 0 }
// expected-error@-1 {{subscript cannot be marked @objc because it has generic parameters}}
}
|
apache-2.0
|
361ab1417e0b0b4f85130204f0058978
| 39.727235 | 350 | 0.703914 | 3.909644 | false | false | false | false |
Shuangzuan/Pew
|
Pew/ParallaxNode.swift
|
1
|
1236
|
//
// ParallaxNode.swift
// Pew
//
// Created by Shuangzuan He on 4/17/15.
// Copyright (c) 2015 Pretty Seven. All rights reserved.
//
import SpriteKit
class ParallaxNode: SKNode {
private let velocity: CGPoint
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(velocity: CGPoint) {
self.velocity = velocity
super.init()
}
func addChild(node: SKSpriteNode, parallaxRatio: CGFloat) {
node.userData = NSMutableDictionary(object: parallaxRatio, forKey: "ParallaxRatio")
super.addChild(node)
}
func update(deltaTime: NSTimeInterval) {
for (idx, node) in enumerate(children) {
if let node = node as? SKSpriteNode {
if let userData = node.userData {
if let parallaxRatio = userData.objectForKey("ParallaxRatio") as? CGFloat {
let childVelocity = velocity * parallaxRatio
let offset = childVelocity * CGFloat(deltaTime)
node.position = node.position + offset
}
}
}
}
}
}
|
mit
|
c1921a75389932d4ddafee725aa89657
| 26.466667 | 95 | 0.555016 | 4.866142 | false | false | false | false |
CodingGirl1208/FlowerField
|
FlowerField/FlowerField/MallsTableViewController.swift
|
1
|
3244
|
//
// MallsTableViewController.swift
// FlowerField
//
// Created by 易屋之家 on 16/8/9.
// Copyright © 2016年 xuping. All rights reserved.
//
import UIKit
class MallsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
a49dfbdfa0258facf10e6799e325274f
| 33.031579 | 157 | 0.687287 | 5.498299 | false | false | false | false |
mohitathwani/swift-corelibs-foundation
|
Foundation/NSStream.swift
|
1
|
14040
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal extension UInt {
init(_ status: CFStreamStatus) {
self.init(status.rawValue)
}
}
#endif
extension Stream {
public struct PropertyKey : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: Stream.PropertyKey, rhs: Stream.PropertyKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: Stream.PropertyKey, rhs: Stream.PropertyKey) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
public enum Status : UInt {
case notOpen
case opening
case open
case reading
case writing
case atEnd
case closed
case error
}
public struct Event : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
// NOTE: on darwin these are vars
public static let openCompleted = Event(rawValue: 1 << 0)
public static let hasBytesAvailable = Event(rawValue: 1 << 1)
public static let hasSpaceAvailable = Event(rawValue: 1 << 2)
public static let errorOccurred = Event(rawValue: 1 << 3)
public static let endEncountered = Event(rawValue: 1 << 4)
}
}
// NSStream is an abstract class encapsulating the common API to InputStream and OutputStream.
// Subclassers of InputStream and OutputStream must also implement these methods.
open class Stream: NSObject {
public override init() {
}
open func open() {
NSRequiresConcreteImplementation()
}
open func close() {
NSRequiresConcreteImplementation()
}
open weak var delegate: StreamDelegate?
// By default, a stream is its own delegate, and subclassers of InputStream and OutputStream must maintain this contract. [someStream setDelegate:nil] must restore this behavior. As usual, delegates are not retained.
open func property(forKey key: PropertyKey) -> AnyObject? {
NSUnimplemented()
}
open func setProperty(_ property: AnyObject?, forKey key: PropertyKey) -> Bool {
NSUnimplemented()
}
// Re-enable once run loop is compiled on all platforms
open func schedule(in aRunLoop: RunLoop, forMode mode: RunLoopMode) {
NSUnimplemented()
}
open func remove(from aRunLoop: RunLoop, forMode mode: RunLoopMode) {
NSUnimplemented()
}
open var streamStatus: Status {
NSRequiresConcreteImplementation()
}
open var streamError: Error? {
NSRequiresConcreteImplementation()
}
}
// InputStream is an abstract class representing the base functionality of a read stream.
// Subclassers are required to implement these methods.
open class InputStream: Stream {
internal let _stream: CFReadStream!
// reads up to length bytes into the supplied buffer, which must be at least of size len. Returns the actual number of bytes read.
open func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int {
return CFReadStreamRead(_stream, buffer, CFIndex(len._bridgeToObjectiveC()))
}
// returns in O(1) a pointer to the buffer in 'buffer' and by reference in 'len' how many bytes are available. This buffer is only valid until the next stream operation. Subclassers may return NO for this if it is not appropriate for the stream type. This may return NO if the buffer is not available.
open func getBuffer(_ buffer: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>, length len: UnsafeMutablePointer<Int>) -> Bool {
NSUnimplemented()
}
// returns YES if the stream has bytes available or if it impossible to tell without actually doing the read.
open var hasBytesAvailable: Bool {
return CFReadStreamHasBytesAvailable(_stream)
}
public init(data: Data) {
_stream = CFReadStreamCreateWithData(kCFAllocatorSystemDefault, data._cfObject)
}
public init?(url: URL) {
_stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url._cfObject)
}
public convenience init?(fileAtPath path: String) {
self.init(url: URL(fileURLWithPath: path))
}
open override func open() {
CFReadStreamOpen(_stream)
}
open override func close() {
CFReadStreamClose(_stream)
}
open override var streamStatus: Status {
return Stream.Status(rawValue: UInt(CFReadStreamGetStatus(_stream)))!
}
open override var streamError: Error? {
return _CFReadStreamCopyError(_stream)
}
}
// OutputStream is an abstract class representing the base functionality of a write stream.
// Subclassers are required to implement these methods.
// Currently this is left as named OutputStream due to conflicts with the standard library's text streaming target protocol named OutputStream (which ideally should be renamed)
open class OutputStream : Stream {
private var _stream: CFWriteStream!
// writes the bytes from the specified buffer to the stream up to len bytes. Returns the number of bytes actually written.
open func write(_ buffer: UnsafePointer<UInt8>, maxLength len: Int) -> Int {
return CFWriteStreamWrite(_stream, buffer, len)
}
// returns YES if the stream can be written to or if it is impossible to tell without actually doing the write.
open var hasSpaceAvailable: Bool {
return CFWriteStreamCanAcceptBytes(_stream)
}
// NOTE: on Darwin this is 'open class func toMemory() -> Self'
required public init(toMemory: ()) {
_stream = CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorDefault, kCFAllocatorDefault)
}
// TODO: this should use the real buffer API
public init(toBuffer buffer: UnsafeMutablePointer<UInt8>, capacity: Int) {
_stream = CFWriteStreamCreateWithBuffer(kCFAllocatorSystemDefault, buffer, capacity)
}
public init?(url: URL, append shouldAppend: Bool) {
_stream = CFWriteStreamCreateWithFile(kCFAllocatorSystemDefault, url._cfObject)
CFWriteStreamSetProperty(_stream, kCFStreamPropertyAppendToFile, shouldAppend._cfObject)
}
public convenience init?(toFileAtPath path: String, append shouldAppend: Bool) {
self.init(url: URL(fileURLWithPath: path), append: shouldAppend)
}
open override func open() {
CFWriteStreamOpen(_stream)
}
open override func close() {
CFWriteStreamClose(_stream)
}
open override var streamStatus: Status {
return Stream.Status(rawValue: UInt(CFWriteStreamGetStatus(_stream)))!
}
open class func toMemory() -> Self {
return self.init(toMemory: ())
}
open override func property(forKey key: PropertyKey) -> AnyObject? {
return CFWriteStreamCopyProperty(_stream, key.rawValue._cfObject)
}
open override func setProperty(_ property: AnyObject?, forKey key: PropertyKey) -> Bool {
return CFWriteStreamSetProperty(_stream, key.rawValue._cfObject, property)
}
open override var streamError: Error? {
return _CFWriteStreamCopyError(_stream)
}
}
// Discussion of this API is ongoing for its usage of AutoreleasingUnsafeMutablePointer
#if false
extension Stream {
open class func getStreamsToHost(withName hostname: String, port: Int, inputStream: AutoreleasingUnsafeMutablePointer<InputStream?>?, outputStream: AutoreleasingUnsafeMutablePointer<OutputStream?>?) {
NSUnimplemented()
}
}
extension Stream {
open class func getBoundStreams(withBufferSize bufferSize: Int, inputStream: AutoreleasingUnsafeMutablePointer<InputStream?>?, outputStream: AutoreleasingUnsafeMutablePointer<OutputStream?>?) {
NSUnimplemented()
}
}
#endif
extension StreamDelegate {
func stream(_ aStream: Stream, handleEvent eventCode: Stream.Event) { }
}
public protocol StreamDelegate : class {
func stream(_ aStream: Stream, handleEvent eventCode: Stream.Event)
}
// MARK: -
extension Stream.PropertyKey {
public static let socketSecurityLevelKey = Stream.PropertyKey(rawValue: "kCFStreamPropertySocketSecurityLevel")
public static let socksProxyConfigurationKey = Stream.PropertyKey(rawValue: "kCFStreamPropertySOCKSProxy")
public static let dataWrittenToMemoryStreamKey = Stream.PropertyKey(rawValue: "kCFStreamPropertyDataWritten")
public static let fileCurrentOffsetKey = Stream.PropertyKey(rawValue: "kCFStreamPropertyFileCurrentOffset")
public static let networkServiceType = Stream.PropertyKey(rawValue: "kCFStreamNetworkServiceType")
}
// MARK: -
public struct StreamSocketSecurityLevel : RawRepresentable, Equatable, Hashable, Comparable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: StreamSocketSecurityLevel, rhs: StreamSocketSecurityLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: StreamSocketSecurityLevel, rhs: StreamSocketSecurityLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension StreamSocketSecurityLevel {
public static let none = StreamSocketSecurityLevel(rawValue: "kCFStreamSocketSecurityLevelNone")
public static let ssLv2 = StreamSocketSecurityLevel(rawValue: "NSStreamSocketSecurityLevelSSLv2")
public static let ssLv3 = StreamSocketSecurityLevel(rawValue: "NSStreamSocketSecurityLevelSSLv3")
public static let tlSv1 = StreamSocketSecurityLevel(rawValue: "kCFStreamSocketSecurityLevelTLSv1")
public static let negotiatedSSL = StreamSocketSecurityLevel(rawValue: "kCFStreamSocketSecurityLevelNegotiatedSSL")
}
// MARK: -
public struct StreamSOCKSProxyConfiguration : RawRepresentable, Equatable, Hashable, Comparable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: StreamSOCKSProxyConfiguration, rhs: StreamSOCKSProxyConfiguration) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: StreamSOCKSProxyConfiguration, rhs: StreamSOCKSProxyConfiguration) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension StreamSOCKSProxyConfiguration {
public static let hostKey = StreamSOCKSProxyConfiguration(rawValue: "NSStreamSOCKSProxyKey")
public static let portKey = StreamSOCKSProxyConfiguration(rawValue: "NSStreamSOCKSPortKey")
public static let versionKey = StreamSOCKSProxyConfiguration(rawValue: "kCFStreamPropertySOCKSVersion")
public static let userKey = StreamSOCKSProxyConfiguration(rawValue: "kCFStreamPropertySOCKSUser")
public static let passwordKey = StreamSOCKSProxyConfiguration(rawValue: "kCFStreamPropertySOCKSPassword")
}
// MARK: -
public struct StreamSOCKSProxyVersion : RawRepresentable, Equatable, Hashable, Comparable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: StreamSOCKSProxyVersion, rhs: StreamSOCKSProxyVersion) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: StreamSOCKSProxyVersion, rhs: StreamSOCKSProxyVersion) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension StreamSOCKSProxyVersion {
public static let version4 = StreamSOCKSProxyVersion(rawValue: "kCFStreamSocketSOCKSVersion4")
public static let version5 = StreamSOCKSProxyVersion(rawValue: "kCFStreamSocketSOCKSVersion5")
}
// MARK: - Supported network service types
public struct StreamNetworkServiceTypeValue : RawRepresentable, Equatable, Hashable, Comparable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: StreamNetworkServiceTypeValue, rhs: StreamNetworkServiceTypeValue) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: StreamNetworkServiceTypeValue, rhs: StreamNetworkServiceTypeValue) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension StreamNetworkServiceTypeValue {
public static let voIP = StreamNetworkServiceTypeValue(rawValue: "kCFStreamNetworkServiceTypeVoIP")
public static let video = StreamNetworkServiceTypeValue(rawValue: "kCFStreamNetworkServiceTypeVideo")
public static let background = StreamNetworkServiceTypeValue(rawValue: "kCFStreamNetworkServiceTypeBackground")
public static let voice = StreamNetworkServiceTypeValue(rawValue: "kCFStreamNetworkServiceTypeVoice")
public static let callSignaling = StreamNetworkServiceTypeValue(rawValue: "kCFStreamNetworkServiceTypeVoice")
}
// MARK: - Error Domains
// NSString constants for error domains.
public let NSStreamSocketSSLErrorDomain: String = "NSStreamSocketSSLErrorDomain"
// SSL errors are to be interpreted via <Security/SecureTransport.h>
public let NSStreamSOCKSErrorDomain: String = "NSStreamSOCKSErrorDomain"
|
apache-2.0
|
6c705e07c94062f95075ab8eb7c58146
| 37.152174 | 305 | 0.714459 | 5.346535 | false | false | false | false |
BridgeTheGap/KRWalkThrough
|
KRWalkThrough/Classes/TutorialManager.swift
|
1
|
3250
|
//
// TutorialManager.swift
// Tutorial
//
// Created by Joshua Park on 5/27/16.
// Copyright © 2016 Knowre. All rights reserved.
//
import UIKit
open class TutorialManager: NSObject {
open static let shared = TutorialManager()
open var shouldShowTutorial = true
open private(set) var items = [String: TutorialItem]()
open private(set) var currentItem: TutorialItem?
fileprivate let blankItem: TutorialItem
fileprivate let transparentItem: TutorialItem
fileprivate override init() {
let blankView = TutorialView(frame: UIScreen.main.bounds)
blankItem = TutorialItem(view: blankView, identifier: "blankItem")
let transparentView = TutorialView(frame: UIScreen.main.bounds)
transparentView.backgroundColor = UIColor.clear
transparentItem = TutorialItem(view: transparentView, identifier: "transparentItem")
}
open func register(item: TutorialItem) {
items[item.identifier] = item
}
open func deregister(item: TutorialItem) {
items[item.identifier] = nil
}
open func deregisterAllItems() {
for key in items.keys {
items[key] = nil
}
}
open func performNextAction() {
currentItem?.nextAction?()
}
open func showTutorial(withIdentifier identifier: String) {
guard shouldShowTutorial else {
print("TutorialManager.shouldShowTutorial = false\nTutorial Manager will return without showing tutorial.")
return
}
guard let window = UIApplication.shared.delegate?.window else {
fatalError("UIApplication delegate's window is missing.")
}
guard let item = items[identifier] else {
print("ERROR: \(TutorialManager.self) line #\(#line) - \(#function)\n** Reason: No registered item with identifier: \(identifier)")
return
}
if blankItem.view.superview != nil { blankItem.view.removeFromSuperview() }
if transparentItem.view.superview != nil { transparentItem.view.removeFromSuperview() }
window?.addSubview(item.view)
window?.setNeedsLayout()
if currentItem?.view.superview != nil { currentItem?.view.removeFromSuperview() }
currentItem = item
}
open func showBlankItem(withAction action: Bool = false) {
UIApplication.shared.delegate!.window!!.addSubview(blankItem.view)
UIApplication.shared.delegate!.window!!.setNeedsLayout()
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
open func showTransparentItem(withAction action: Bool = false) {
UIApplication.shared.delegate!.window!!.addSubview(transparentItem.view)
UIApplication.shared.delegate!.window!!.setNeedsLayout()
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
open func hideTutorial(withAction action: Bool = false) {
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
}
|
mit
|
56d25d18d577a807bcd7746fed70ddaf
| 32.84375 | 143 | 0.643583 | 5.037209 | false | false | false | false |
tgu/HAP
|
Sources/HAP/Server/Device.SetupCode.swift
|
1
|
1906
|
import Cryptor
import Foundation
#if os(Linux)
import Glibc
#endif
import Regex
extension Device {
public enum SetupCode: ExpressibleByStringLiteral {
case random
case override(String)
public init(stringLiteral value: StringLiteralType) {
self = .override(value)
}
public var isValid: Bool {
switch self {
case .override(let setupCode):
return SetupCode.isValid(setupCode)
case .random:
return true
}
}
/// HAP Specification lists certain setup codes as invalid.
static private func isValid(_ setupCode: String) -> Bool {
let invalidCodes = ["000-00-000", "111-11-111", "222-22-222",
"333-33-333", "444-44-444", "555-55-555",
"666-66-666", "777-77-777", "888-88-888",
"999-99-999", "123-45-678", "876-54-321"]
return (setupCode =~ "^\\d{3}-\\d{2}-\\d{3}$") && !invalidCodes.contains(setupCode)
}
/// Generate a valid random setup code, used to pair with the device.
static func generate() -> String {
var setupCode = ""
repeat {
setupCode = String(format: "%03ld-%02ld-%03ld",
arc4random_uniform(1000),
arc4random_uniform(100),
arc4random_uniform(1000))
} while !SetupCode.isValid(setupCode)
return setupCode
}
/// Generate a random four character setup key, used in setupURI and setupHash
static internal func generateSetupKey() -> String {
return String(arc4random_uniform(1679616), radix: 36, uppercase: true)
.padLeft(toLength: 4, withPad: "0")
}
}
}
|
mit
|
392cf093805f3d8eb8aad4250cbd7147
| 34.962264 | 95 | 0.517838 | 4.538095 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
OctoPhone/View Related/Print Profiles/PrintProfilesViewController.swift
|
1
|
3502
|
//
// PrintProfilesViewController.swift
// OctoPhone
//
// Created by Josef Dolezal on 03/04/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
/// Print profile list flow delegate
protocol PrintProfilesViewControllerDelegate: class {
/// Called when user selected printer profile
///
/// - Parameter printerProfile: Selected printer profile
func selectedPrinterProfile(_ printerProfile: PrinterProfile)
/// Called when user tapped add printer button
func addButtonTappped()
}
/// Printer profiles list
class PrintProfilesViewController: BaseCollectionViewController {
// MARK: - Properties
/// Controller logic
fileprivate var viewModel: PrintProfilesViewModelType!
/// Add profile button
lazy private var addButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .add, target: self,
action: #selector(addButtonTapped))
return button
}()
// MARK: - Initializers
convenience init(viewModel: PrintProfilesViewModelType) {
self.init(collectionViewLayout: UICollectionViewFlowLayout())
self.viewModel = viewModel
bindViewModel()
}
// MARK: - Controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = addButton
collectionView?.register(PrintProfileCollectionViewCell.self,
forCellWithReuseIdentifier: PrintProfileCollectionViewCell.identifier)
}
// MARK: - Internal logic
/// Add button UI action
func addButtonTapped() {
viewModel.inputs.addButtonTapped()
}
/// Binds outputs of View Model to UI and converts
/// user interaction to View Model inputs
private func bindViewModel() {
if let collectionView = collectionView {
collectionView.reactive.reloadData <~ viewModel.outputs.profilesChanged
}
}
}
// MARK: - UICollectionViewDataSource
extension PrintProfilesViewController {
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return viewModel.outputs.profilesCount.value
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: PrintProfileCollectionViewCell.identifier,
for: indexPath) as! PrintProfileCollectionViewCell
cell.viewModel.value = viewModel.outputs.printProfileCellViewModel(for: indexPath.row)
return cell
}
}
// MARK: - UICollectionViewDelegate
extension PrintProfilesViewController {
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
viewModel.inputs.selectedPrinterProfile(at: indexPath.row)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension PrintProfilesViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 44)
}
}
|
mit
|
f1834212f38eb6cba355f816029f847f
| 29.982301 | 103 | 0.687232 | 6.036207 | false | false | false | false |
didisouzacosta/ASAlertViewController
|
ASAlertViewController/Classes/ASAlertSelect/ASAlertSelectAction.swift
|
1
|
1263
|
//
// ASAlertSelectAction.swift
// Pods
//
// Created by Adriano Souza Costa on 19/04/17.
//
//
import Foundation
open class ASAlertSelectAction {
fileprivate var _title: String
fileprivate var _detail: String?
fileprivate var _image: UIImage?
fileprivate var _isSelected: Bool
fileprivate var _onAction: (() -> Void)?
public init(title: String, isSelected: Bool = false, detail: String? = nil, image: UIImage? = nil, onAction: (() -> Void)? = nil) {
_title = title
_detail = detail
_image = image
_isSelected = isSelected
_onAction = onAction
}
}
extension ASAlertSelectAction: ASAlertSelectOption {
public var title: String {
get { return _title }
set { _title = newValue }
}
public var detail: String? {
get { return _detail }
set { _detail = newValue }
}
public var image: UIImage? {
get { return _image }
set { _image = newValue }
}
public var isSelected: Bool {
get { return _isSelected }
set { _isSelected = newValue }
}
public var onAction: (() -> Void)? {
get { return _onAction }
set { _onAction = newValue }
}
}
|
mit
|
7672b0d1fa7f5de4c2c21ea7ae3a7907
| 21.553571 | 135 | 0.562945 | 4.21 | false | false | false | false |
walokra/Haikara
|
Watch Extension/NewsInterfaceController.swift
|
1
|
2720
|
//
// WatchInterfaceController.swift
// Watch Extension
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Marko Wallin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import WatchKit
import Foundation
class NewsInterfaceController: WKInterfaceController {
@IBOutlet var newsTable: WKInterfaceTable!
var entries = [Entry]()
override func awake(withContext: Any?) {
super.awake(withContext: withContext)
getNews(1)
}
override func table(_: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
let entry = entries[rowIndex]
// let controllers = ["NewsEntry", "ReadEntry"]
// presentController(withNames: controllers, contexts:[entry, entry])
presentController(withName: "NewsEntry", context: entry)
}
func getNews(_ page: Int) -> Void {
#if DEBUG
print("WatchInterfaceController, getNews: checking if entries need refreshing")
#endif
// with trailing closure we get the results that we passed the closure back in async function
HighFiApi.getNews(page, section: "uutiset",
completionHandler: { (result) in
// self.entries = Array(result[0..<5])
self.entries = Array(result)
#if DEBUG
print("entries=\(self.entries.count)")
#endif
self.newsTable.setNumberOfRows(self.entries.count, withRowType: "NewsRow")
for index in 0..<self.newsTable.numberOfRows {
if let controller = self.newsTable.rowController(at: index) as? NewsRowController {
controller.entry = self.entries[index]
}
}
}
, failureHandler: {(error) in
#if DEBUG
print("entries=\(error)")
#endif
}
)
}
}
|
mit
|
c4ee110a7205f760b5f24cc8c3f1bce3
| 33.871795 | 96 | 0.698529 | 4.023669 | false | false | false | false |
stripe/stripe-ios
|
StripePayments/StripePayments/API Bindings/Models/PaymentIntents/STPPaymentIntentShippingDetailsParams.swift
|
1
|
3468
|
//
// STPPaymentIntentShippingDetailsParams.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 4/27/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import Foundation
/// Shipping information for a PaymentIntent
/// - seealso: https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping
public class STPPaymentIntentShippingDetailsParams: NSObject {
/// Shipping address.
@objc public var address: STPPaymentIntentShippingDetailsAddressParams
/// Recipient name.
@objc public var name: String
/// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.
@objc public var carrier: String?
/// Recipient phone (including extension).
@objc public var phone: String?
/// The tracking number for a physical product, obtained from the delivery service. If multiple tracking numbers were generated for this purchase, please separate them with commas.
@objc public var trackingNumber: String?
/// :nodoc:
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// Initialize an `STPPaymentIntentShippingDetailsParams` with required properties.
@objc
public init(
address: STPPaymentIntentShippingDetailsAddressParams,
name: String
) {
self.address = address
self.name = name
super.init()
}
/// :nodoc:
@objc public override var description: String {
let props: [String] = [
// Object
String(
format: "%@: %p",
NSStringFromClass(STPPaymentIntentShippingDetailsParams.self),
self
),
// Properties
"address = \(address)",
"name = \(name)",
"carrier = \(String(describing: carrier))",
"phone = \(String(describing: phone))",
"trackingNumber = \(String(describing: trackingNumber))",
]
return "<\(props.joined(separator: "; "))>"
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Self else {
return false
}
return other.name == name && other.carrier == carrier && other.phone == phone
&& other.trackingNumber == trackingNumber && other.address == address
}
}
// MARK: - STPFormEncodable
extension STPPaymentIntentShippingDetailsParams: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:address)): "address",
NSStringFromSelector(#selector(getter:name)): "name",
NSStringFromSelector(#selector(getter:carrier)): "carrier",
NSStringFromSelector(#selector(getter:phone)): "phone",
NSStringFromSelector(#selector(getter:trackingNumber)): "tracking_number",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
// MARK: - NSCopying
extension STPPaymentIntentShippingDetailsParams: NSCopying {
/// :nodoc:
@objc
public func copy(with zone: NSZone? = nil) -> Any {
let copy = STPPaymentIntentShippingDetailsParams(address: address, name: name)
copy.carrier = carrier
copy.phone = phone
copy.trackingNumber = trackingNumber
copy.additionalAPIParameters = additionalAPIParameters
return copy
}
}
|
mit
|
407f25afe080fb1eacdd2b61c888a238
| 30.518182 | 184 | 0.639746 | 4.889986 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/Pods/FacebookShare/Sources/Share/Content/OpenGraph/OpenGraphShareContent.swift
|
13
|
3824
|
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import FBSDKShareKit
/**
A model for Open Graph content to be shared.
*/
public struct OpenGraphShareContent {
public typealias Result = PostSharingResult
/// The Open Graph action to be shared.
public var action: OpenGraphAction?
/// Property name that points to the primary Open Graph Object in the action. This is used for rendering the preview of the share.
public var previewPropertyName: OpenGraphPropertyName?
/**
Create a new OpenGraphShareContent.
- parameter action: The action to be shared.
- parameter previewPropertyName: Property name that points to the primary Open Graph Object in the action.
*/
public init(action: OpenGraphAction? = nil, previewPropertyName: OpenGraphPropertyName? = nil) {
self.action = action
self.previewPropertyName = previewPropertyName
}
//--------------------------------------
// MARK: - ContentProtocol
//--------------------------------------
/**
URL for the content being shared.
This URL will be checked for all link meta tags for linking in platform specific ways.
See documentation for [App Links](https://developers.facebook.com/docs/applinks/)
*/
public var url: URL?
/// Hashtag for the content being shared.
public var hashtag: Hashtag?
/**
List of IDs for taggable people to tag with this content.
See documentation for [Taggable Friends](https://developers.facebook.com/docs/graph-api/reference/user/taggable_friends)
*/
public var taggedPeopleIds: [String]?
/// The ID for a place to tag with this content.
public var placeId: String?
/// A value to be added to the referrer URL when a person follows a link from this shared content on feed.
public var referer: String?
}
extension OpenGraphShareContent: Equatable {
/**
Compares two `OpenGraphContent`s for equality.
- parameter lhs: The first content to compare.
- parameter rhs: The second content to comare.
- returns: Whether or not the content are equal.
*/
public static func == (lhs: OpenGraphShareContent, rhs: OpenGraphShareContent) -> Bool {
return lhs.sdkSharingContentRepresentation.isEqual(rhs.sdkSharingContentRepresentation)
}
}
extension OpenGraphShareContent: SDKBridgedContent {
internal var sdkSharingContentRepresentation: FBSDKSharingContent {
let sdkContent = FBSDKShareOpenGraphContent()
sdkContent.action = action?.sdkActionRepresentation
sdkContent.previewPropertyName = previewPropertyName?.rawValue
sdkContent.contentURL = url
sdkContent.hashtag = hashtag?.sdkHashtagRepresentation
sdkContent.peopleIDs = taggedPeopleIds
sdkContent.placeID = placeId
sdkContent.ref = referer
return sdkContent
}
}
|
mit
|
7a37618e2977a2c07ad520042932415d
| 37.24 | 132 | 0.735879 | 4.774032 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/Base/Views/ZSBaseCellAdapter.swift
|
1
|
1276
|
//
// ZSBaseCellAdapter.swift
// zhuishushenqi
//
// Created by caony on 2018/8/27.
// Copyright © 2018年 QS. All rights reserved.
//
import Foundation
class ZSBaseCellAdapter:NSObject ,ZSCellAdapterProtocol {
var dataSource:[Any] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell!
if let cls = registerCellClasses().first {
cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(cls))
} else {
cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
init(_ tableView:UITableView,dataSource:[Any]) {
super.init()
self.dataSource = dataSource
for cls in registerCellClasses() {
tableView.register(cls, forCellReuseIdentifier: NSStringFromClass(cls))
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func registerCellClasses() ->[AnyClass] {
return []
}
}
|
mit
|
be3ef5a508e7ab894cd86d47da7ec287
| 26.085106 | 105 | 0.641791 | 5.195918 | false | false | false | false |
ello/ello-ios
|
Specs/Controllers/Profile/Cells/ProfileHeaderNamesCellSpec.swift
|
1
|
1157
|
////
/// ProfileHeaderNamesCellSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ProfileHeaderNamesCellSpec: QuickSpec {
override func spec() {
describe("ProfileHeaderNamesCell") {
it("horizontal snapshots") {
let subject = ProfileHeaderNamesCell(
frame: CGRect(
origin: .zero,
size: CGSize(width: 375, height: 60)
)
)
subject.name = "Jim"
subject.username = "@jimmy"
expectValidSnapshot(subject, named: "ProfileHeaderNamesCell-horizontal")
}
it("vertical snapshots") {
let subject = ProfileHeaderNamesCell(
frame: CGRect(
origin: .zero,
size: CGSize(width: 300, height: 80)
)
)
subject.name = "Jimmy Jim Jim Shabadoo"
subject.username = "@jimmy"
expectValidSnapshot(subject, named: "ProfileHeaderNamesCell-vertical")
}
}
}
}
|
mit
|
7ced7af5443a69f88188cd86666bc047
| 30.27027 | 88 | 0.487468 | 5.235294 | false | false | false | false |
tndatacommons/Compass-iOS
|
Compass/src/Util/FeedDataLoader.swift
|
1
|
15035
|
//
// FeedDataLoader.swift
// Compass
//
// Created by Ismael Alonso on 10/7/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import Foundation
import Just
import ObjectMapper
/// Handles loading all required data for the feed to display.
/**
Loads the FeedData bundle, Actions, and goals on demand. The FeedData bundle is accompanied by
three Actions, one CustomAction, one UserAction, and other of either, and none to five Goals,
depending on availability. Loaded FeedData is placed in SharedData.feedData, while goals loaded
on demand are delivered through a closure.
- Author: Ismael Alonso
*/
final class FeedDataLoader{
//MARK: Singleton and instance retrieval
private static var loader: FeedDataLoader?
/// FeedDataLoader instance getter.
/**
Gets the available instance of FeedDataLoader, if there isn't one it creates it.
- Returns: an instance of FeedDataLoader.
*/
static func getInstance() -> FeedDataLoader{
if loader == nil{
loader = FeedDataLoader()
}
return loader!
}
//MARK: Attributes
private var feedData: FeedData?
private var goalBatch = [Goal]()
//¡¡IMPORTANT!!
//If the URLs are null, the data has been loaded but the result set was empty
//If the URLs are the empty string, the data has not yet been loaded
//This is because the API returns NULL as the next URL in the last page of the dataset
private var getNextUserActionUrl: String? = ""
private var getNextCustomActionUrl: String? = ""
//Goal load is not concurrent, so the above comment does not apply to this URL
private var getNextGoalBatchUrl: String?
//Initial run flags
private var initialActionLoadRunning = true
private var initialGoalLoadRunning = true
//Callback stores
private var dataLoadCallback: ((Bool) -> Void)?
private var goalLoadCallback: ([Goal]? -> Void)?
//MARK: Resetting method
/// Resets the instance of FeedDataLoader.
private func initialize(){
feedData = nil
goalBatch = [Goal]()
getNextUserActionUrl = ""
getNextCustomActionUrl = ""
initialActionLoadRunning = true
initialGoalLoadRunning = true
}
//MARK: Internal checking methods
/// Tells whether initial feed data is loaded.
/**
Three conditions must be satisified, initial action load is over, initial goal load is over,
and the FeedData bundle exists. Non-existing FeedData indicates that either the process has
not yet started, the process has started but the FeedData GET request has not been satisfied,
or that there was an error along the way that made impossible to load the FeedData.
- Returns: true if the feed data is loaded, false otherwise.
*/
private func isFeedDataLoaded() -> Bool{
return !initialActionLoadRunning && !initialGoalLoadRunning && feedData != nil
}
/// Tells whether initial data load for either UserActions or CustomActions is over.
/**
The relevance of this method is that it is able to tell if they are complete individually,
as opposed to the initialActionLoadRunning flag, which tells whether both of them are
complete or not. Next action urls have three states: nil, empty, and non-empty. If nil,
there are no more actions to load; if empty, the initial action load is still in progress;
and if non-empty, at least an action has been loaded.
- parameter url: the url of the next action to be loaded for either UserActions or
CustomActions.
- Returns: true if the url is non-empty.
*/
private func isInitialLoadOver(url: String?) -> Bool{
return url == nil || !url!.isEmpty;
}
//MARK: User interaction methods
/// Triggers the initial FeedData load.
/**
This methods calls initialize(), which resets the instance to initial state.
- parameter callback: a closure taking a boolean which represents load success or failure.
*/
func load(callback: (Bool) -> Void){
dataLoadCallback = callback
initialize()
fetchFeedData();
}
/// Triggers the process that loads the next UserAction.
/**
UserActions loaded this way are placed directly in the FeedData buffer.
*/
func loadNextUserAction(){
if getNextUserActionUrl != nil{
fetchUserAction(getNextUserActionUrl!)
}
}
/// Triggers the process that loads the next CustomAction.
/**
CustomActions loaded this way are placed directly in the FeedData buffer.
*/
func loadNextCustomAction(){
if getNextCustomActionUrl != nil{
fetchCustomAction(getNextCustomActionUrl!)
}
}
/// Tells whether more goals can be loaded.
/**
For more goals to be loaded, two conditions must be satisfied; there must be a loaded instance
of FeedData, and there need to be more goals.
- Returns: true if more goals can be loaded, false otherwise.
*/
func canLoadMoreGoals() -> Bool{
return isFeedDataLoaded() && getNextGoalBatchUrl != nil
}
/// Loads the next goal batch.
/**
Goals are only loaded if the conditions in canLoadMoreGoals() are satisfied. If they can't,
the callback closure will be called with a null parameter.
- parameter callback: a closure taking an optional list of goals as a parameter.
*/
func loadNextGoalBatch(callback: ([Goal]?) -> Void){
if canLoadMoreGoals(){
goalLoadCallback = callback
//Decide which kind of goals to load
if getNextGoalBatchUrl!.containsString("custom"){
fetchCustomGoals(getNextGoalBatchUrl!)
}
else{
fetchUserGoals(getNextGoalBatchUrl!)
}
}
else{
callback(nil)
}
}
//MARK: Internal data retrieval methods
/// Fires the request to the endpoint that exposes FeedData.
private func fetchFeedData(){
Just.get(API.getFeedDataUrl(), headers: SharedData.user.getHeaderMap()){ (response) in
print(response.contentStr)
if response.ok{
self.onFeedDataLoaded(Mapper<FeedDataList>().map(response.contentStr)!.feedData[0])
}
else{
self.dispatchFeedDataLoadFailed()
}
}
}
/// Fires the request to fetch a UserAction.
private func fetchUserAction(url: String){
Just.get(url, headers: SharedData.user.getHeaderMap()){ (response) in
if response.ok{
self.processUserAction(Mapper<UserActionList>().map(response.contentStr)!)
}
else{
if (!self.isFeedDataLoaded()){
self.dispatchFeedDataLoadFailed()
}
else{
self.feedData?.setNextUserAction(nil)
}
}
}
}
/// Fires the request to fetch a CustomAction.
private func fetchCustomAction(url: String){
Just.get(url, headers: SharedData.user.getHeaderMap()){ (response) in
if response.ok{
self.processCustomAction(Mapper<CustomActionList>().map(response.contentStr)!)
}
else{
if (!self.isFeedDataLoaded()){
self.dispatchFeedDataLoadFailed()
}
else{
self.feedData?.setNextCustomAction(nil)
}
}
}
}
/// Fires the request to fetch a batch of CustomGoals.
private func fetchCustomGoals(url: String){
Just.get(url, headers: SharedData.user.getHeaderMap()){ (response) in
if response.ok{
self.processCustomGoals(Mapper<CustomGoalList>().map(response.contentStr)!)
}
else{
if (!self.isFeedDataLoaded()){
self.dispatchFeedDataLoadFailed()
}
else{
self.dispatchGoalLoadFailed()
}
}
}
}
/// Fires the request to fetch a batch of UserGoals.
private func fetchUserGoals(url: String){
Just.get(url, headers: SharedData.user.getHeaderMap()){ (response) in
if response.ok{
self.processUserGoals(Mapper<UserGoalList>().map(response.contentStr)!)
}
else{
if (!self.isFeedDataLoaded()){
self.dispatchFeedDataLoadFailed()
}
else{
self.dispatchGoalLoadFailed()
}
}
}
}
//MARK: Data processing methods
/// Triggers the load of a UserAction, a CustomAction, and the first batch of Goals.
private func onFeedDataLoaded(feedData: FeedData){
self.feedData = feedData
fetchUserAction(API.URL.getTodaysUserActions())
fetchCustomAction(API.URL.getTodaysCustomActions())
fetchCustomGoals(API.getCustomGoalsUrl());
}
/// Decides what to do with a recently fetched UserAction
/**
If there aren't actions to load, which will happen if the user has no actions on the first
call to the endpoint the next UserAction set to the feed data must be nil. Additionally,
if the CustomAction has already loaded, replaceUpNext needs to be called, which will trigger
the load of the action that got bumped, if any. If the goals have finished loading as well
the FeedData is dispatched.
- parameter actionList: the result of parsing the data delivered by the API
*/
private func processUserAction(actionList: UserActionList){
getNextUserActionUrl = actionList.next
var userAction: UserAction?
//The first call to the endpoint may yield no results, in this case the next url will
// be null and the results array will be empty
if actionList.results.isEmpty{
userAction = nil
}
else{
userAction = actionList.results[0]
}
feedData?.setNextUserAction(userAction)
if initialActionLoadRunning && isInitialLoadOver(getNextCustomActionUrl){
//CustomAction has already loaded
feedData?.replaceUpNext()
initialActionLoadRunning = false
if !initialGoalLoadRunning{
dispatchFeedData()
}
}
}
/// Decides what to do with a recently fetched CustomAction
/**
If there aren't actions to load, which will happen if the user has no actions on the first
call to the endpoint the next CustomAction set to the feed data must be nil. Additionally,
if the UserAction has already loaded, replaceUpNext needs to be called, which will trigger
the load of the action that got bumped, if any. If the goals have finished loading as well
the FeedData is dispatched.
- parameter actionList: the result of parsing the data delivered by the API.
*/
private func processCustomAction(actionList: CustomActionList){
getNextCustomActionUrl = actionList.next
var customAction: CustomAction?
//The first call to the endpoint may yield no results, in this case the next url will
// be null and the results array will be empty
if actionList.results.isEmpty{
customAction = nil
}
else{
customAction = actionList.results[0]
}
feedData!.setNextCustomAction(customAction)
if initialActionLoadRunning && isInitialLoadOver(getNextUserActionUrl){
//UserAction has already loaded
feedData!.replaceUpNext()
initialActionLoadRunning = false
if !initialGoalLoadRunning{
dispatchFeedData()
}
}
}
/// Decides what to do with a recently loaded CustomGoal batch.
/**
Sets the next batch url and populates the goal batch list. Loads the first batch of UserGoals
if less than three CustomGoals were delivered, otherwise it dispatches the batch.
- parameter goalList: the result of parsing the data delivered by the API.
*/
private func processCustomGoals(goalList: CustomGoalList){
getNextGoalBatchUrl = goalList.next
for goal in goalList.results{
goalBatch.append(goal)
}
if getNextGoalBatchUrl == nil{
getNextGoalBatchUrl = API.getUserGoalsUrl()
if goalBatch.count < 3{
fetchUserGoals(getNextGoalBatchUrl!)
}
else{
dispatchGoals()
}
}
else{
dispatchGoals()
}
}
/// Decides what to do with a recently loaded UserGoal batch.
/**
Sets the next batch url and dispatches the loaded batch.
- parameter goalList: the result of parsing the data delivered by the API.
*/
private func processUserGoals(goalList: UserGoalList){
getNextGoalBatchUrl = goalList.next
for goal in goalList.results{
goalBatch.append(goal)
}
dispatchGoals()
}
//MARK: Dispatching methods
/// Dispatches the loaded FeedData. If for some reason there ain't no FeedData, dispatches the
/// failed event. Either is done in the UI thread.
private func dispatchFeedData(){
if feedData != nil{
SharedData.feedData = feedData!
dispatch_async(dispatch_get_main_queue(), {
self.dataLoadCallback!(true)
})
}
else{
dispatchFeedDataLoadFailed()
}
}
/// Dispatches a failed load event in the UI thread.
private func dispatchFeedDataLoadFailed(){
feedData = nil
dispatch_async(dispatch_get_main_queue(), {
self.dataLoadCallback?(false)
})
}
/// Dispatches a goal batch in the UI thread if this ain't an initial load.
private func dispatchGoals(){
if initialGoalLoadRunning{
feedData!.addGoals(goalBatch)
goalBatch.removeAll()
if !initialActionLoadRunning{
dispatchFeedData()
}
initialGoalLoadRunning = false
}
else{
dispatch_async(dispatch_get_main_queue(), {
self.goalLoadCallback?(self.goalBatch)
self.goalBatch.removeAll()
})
}
}
/// Dispatches a failed load event in the UI thread.
private func dispatchGoalLoadFailed(){
dispatch_async(dispatch_get_main_queue(), {
self.goalLoadCallback?(nil)
self.goalBatch.removeAll()
})
}
}
|
mit
|
381634bd2a8ac73b35e80639c4f05f93
| 34.203747 | 99 | 0.615553 | 4.967614 | false | false | false | false |
CartoDB/mobile-ios-samples
|
AdvancedMap.Swift/Feature Demo/Device.swift
|
1
|
848
|
//
// Device.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 20/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
class Device {
static func isLandscape() -> Bool {
return UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight
}
static func isTablet() -> Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
static func navigationbarHeight() -> CGFloat {
return ((UIApplication.shared.delegate as! AppDelegate).controller?.navigationBar.frame.height)!
}
static func statusBarHeight() -> CGFloat {
return UIApplication.shared.statusBarFrame.height
}
static func trueY0() -> CGFloat {
return navigationbarHeight() + statusBarHeight()
}
}
|
bsd-2-clause
|
8af54268e8ced686ef1fdd3fd9cd1898
| 24.666667 | 112 | 0.657615 | 4.653846 | false | false | false | false |
material-components/material-components-ios
|
components/NavigationDrawer/examples/BottomDrawerWithChangingContentSize.swift
|
2
|
6793
|
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialBottomAppBar
import MaterialComponents.MaterialNavigationDrawer
import MaterialComponents.MaterialColorScheme
class BottomDrawerWithChangingContentSizeExample: UIViewController {
@objc var colorScheme = MDCSemanticColorScheme(defaults: .material201804)
let bottomAppBar = MDCBottomAppBarView()
let headerViewController = DrawerHeaderViewController()
let contentViewController = DrawerChangingContentSizeViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = colorScheme.backgroundColor
contentViewController.colorScheme = colorScheme
bottomAppBar.isFloatingButtonHidden = true
let barButtonLeadingItem = UIBarButtonItem()
let menuImage = UIImage(named: "system_icons/menu")?.withRenderingMode(.alwaysTemplate)
barButtonLeadingItem.image = menuImage
barButtonLeadingItem.target = self
barButtonLeadingItem.action = #selector(presentNavigationDrawer)
bottomAppBar.leadingBarButtonItems = [barButtonLeadingItem]
bottomAppBar.barTintColor = colorScheme.surfaceColor
let barItemTintColor = colorScheme.onSurfaceColor.withAlphaComponent(0.6)
bottomAppBar.leadingBarItemsTintColor = barItemTintColor
bottomAppBar.trailingBarItemsTintColor = barItemTintColor
bottomAppBar.floatingButton.setBackgroundColor(colorScheme.primaryColor, for: .normal)
bottomAppBar.floatingButton.setTitleColor(colorScheme.onPrimaryColor, for: .normal)
bottomAppBar.floatingButton.setImageTintColor(colorScheme.onPrimaryColor, for: .normal)
view.addSubview(bottomAppBar)
}
private func layoutBottomAppBar() {
let size = bottomAppBar.sizeThatFits(view.bounds.size)
var bottomBarViewFrame = CGRect(
x: 0,
y: view.bounds.size.height - size.height,
width: size.width,
height: size.height)
bottomBarViewFrame.size.height += view.safeAreaInsets.bottom
bottomBarViewFrame.origin.y -= view.safeAreaInsets.bottom
bottomAppBar.frame = bottomBarViewFrame
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutBottomAppBar()
}
@objc func presentNavigationDrawer() {
let bottomDrawerViewController = MDCBottomDrawerViewController()
bottomDrawerViewController.setTopCornersRadius(8, for: .collapsed)
bottomDrawerViewController.setTopCornersRadius(0, for: .expanded)
bottomDrawerViewController.isTopHandleHidden = false
bottomDrawerViewController.contentViewController = contentViewController
bottomDrawerViewController.headerViewController = headerViewController
bottomDrawerViewController.trackingScrollView = contentViewController.collectionView
bottomDrawerViewController.headerViewController?.view.backgroundColor = colorScheme.surfaceColor
bottomDrawerViewController.contentViewController?.view.backgroundColor =
colorScheme.surfaceColor
bottomDrawerViewController.scrimColor = colorScheme.onSurfaceColor.withAlphaComponent(0.32)
present(bottomDrawerViewController, animated: true, completion: nil)
}
}
class DrawerChangingContentSizeViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource
{
@objc var colorScheme: MDCSemanticColorScheme!
let numberOfRowsShort: Int = 2
let numberOfRowsLong: Int = 12
var longList = false
let collectionView: UICollectionView
let layout = UICollectionViewFlowLayout()
init() {
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.frame = CGRect(
x: 0, y: 0, width: self.view.bounds.width,
height: self.view.bounds.height)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
self.view.addSubview(collectionView)
let tapGestureRecognizer = UITapGestureRecognizer(
target: self, action: #selector(didTap(gestureRecognizer:)))
collectionView.addGestureRecognizer(tapGestureRecognizer)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let s = self.view.frame.size.width / 3
layout.itemSize = CGSize(width: s, height: s)
self.preferredContentSize = CGSize(
width: view.bounds.width,
height: layout.collectionViewContentSize.height)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)
-> Int
{
let numberOfRows = longList ? numberOfRowsLong : numberOfRowsShort
return numberOfRows * 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
let colorPick = indexPath.row % 2 == 0
print(indexPath.item)
if longList {
cell.backgroundColor =
colorPick ? colorScheme.secondaryColor : colorScheme.errorColor
} else {
cell.backgroundColor =
colorPick ? colorScheme.secondaryColor : colorScheme.primaryColorVariant
}
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc func didTap(gestureRecognizer: UITapGestureRecognizer) {
longList = !longList
collectionView.reloadData()
self.preferredContentSize = CGSize(
width: self.view.bounds.width,
height: self.layout.collectionViewContentSize.height)
}
}
extension BottomDrawerWithChangingContentSizeExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Navigation Drawer", "Bottom Drawer Changing Content Size"],
"primaryDemo": false,
"presentable": false,
]
}
}
|
apache-2.0
|
afab37bec0bdfacf96ecf32028396d5d
| 37.162921 | 100 | 0.769174 | 5.286381 | false | false | false | false |
roosmaa/Octowire-iOS
|
Octowire/NavigationActions.swift
|
1
|
3071
|
//
// NavigationActions.swift
// Octowire
//
// Created by Mart Roosmaa on 24/02/2017.
// Copyright © 2017 Mart Roosmaa. All rights reserved.
//
import Foundation
import ReSwift
import ReSwiftRecorder
let navigationActionTypeMap: TypeMap = [
NavigationActionStackReplace.type: NavigationActionStackReplace.self,
NavigationActionStackPush.type: NavigationActionStackPush.self,
NavigationActionStackPop.type: NavigationActionStackPop.self]
struct NavigationActionStackReplace: StandardActionConvertible {
static let type = "NAVIGATION_ACTION_STACK_REPLACE"
let routes: [Route]
let animated: Bool
init(routes: [Route], animated: Bool = true) {
self.routes = routes
self.animated = animated
}
init(_ standardAction: StandardAction) {
self.routes = decode(standardAction.payload!["routes"])
self.animated = standardAction.payload!["animated"] as! Bool
}
func toStandardAction() -> StandardAction {
return StandardAction(
type: NavigationActionStackReplace.type,
payload: [
"routes": encode(self.routes),
"animated": self.animated as AnyObject],
isTypedAction: true)
}
}
struct NavigationActionStackPush: StandardActionConvertible {
static let type = "NAVIGATION_ACTION_STACK_PUSH"
let route: Route
let animated: Bool
init(route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
init(_ standardAction: StandardAction) {
self.route = decode(standardAction.payload!["route"])
self.animated = standardAction.payload!["animated"] as! Bool
}
func toStandardAction() -> StandardAction {
return StandardAction(
type: NavigationActionStackPush.type,
payload: [
"route": encode(self.route),
"animated": self.animated as AnyObject],
isTypedAction: true)
}
}
struct NavigationActionStackPop: StandardActionConvertible {
static let type = "NAVIGATION_ACTION_STACK_POP"
let animated: Bool
init(animated: Bool = true) {
self.animated = animated
}
init(_ standardAction: StandardAction) {
self.animated = standardAction.payload!["animated"] as! Bool
}
func toStandardAction() -> StandardAction {
return StandardAction(
type: NavigationActionStackPop.type,
payload: [
"animated": self.animated as AnyObject],
isTypedAction: true)
}
}
private func encode(_ value: [Route]) -> AnyObject {
return value.map({ $0.rawValue }) as AnyObject
}
private func encode(_ value: Route) -> AnyObject {
return value.rawValue as AnyObject
}
private func decode(_ value: AnyObject?) -> Route {
return Route(rawValue: value as! [String: String])!
}
private func decode(_ value: AnyObject?) -> [Route] {
let r = value as! [[String: String]]
return r.map({ Route(rawValue: $0)! })
}
|
mit
|
45dbe1bef48063a76de7a860750032ac
| 27.691589 | 73 | 0.643322 | 4.436416 | false | false | false | false |
iHunterX/SocketIODemo
|
DemoSocketIO/Utils/PAPermissions/Classes/Checks/PAMotionFitnessPermissionsCheck.swift
|
1
|
1489
|
//
// PAMotionFitnessPermissionsCheck.swift
// Pods
//
// Created by Joseph Blau on 9/24/16.
//
//
import UIKit
import CoreMotion
public class PAMotionFitnessPermissionsCheck: PAPermissionsCheck {
let motionActivityManager = CMMotionActivityManager()
public override func checkStatus() {
let currentStatus = self.status
if CMMotionActivityManager.isActivityAvailable() {
if #available(iOS 7.0, *) {
// There is no way to verifty that motion activity is enabled so assume disabled
self.status = .disabled
}
} else {
self.status = .unavailable
}
if self.status != currentStatus {
self.updateStatus()
}
}
public override func defaultAction() {
if #available(iOS 7.0, *) {
self.motionActivityManager.queryActivityStarting(from: Date(), to: Date(), to: OperationQueue.main, withHandler: { (motionActivity, error) in
self.status = motionActivity == nil ? .disabled : .enabled
if let e = error as? NSError {
if e.code == Int(CMErrorNotAuthorized.rawValue) {
self.status = .denied
self.openSettings()
}
}
self.motionActivityManager.stopActivityUpdates()
self.updateStatus()
})
} else {
// Motion & Fitness Only available above iOS 7
}
}
}
|
gpl-3.0
|
76fb0a7f94246905697758d7ddda9fa5
| 25.589286 | 144 | 0.572868 | 4.772436 | false | false | false | false |
icylydia/PlayWithLeetCode
|
412. Fizz Buzz/Solution.swift
|
1
|
296
|
class Solution {
func fizzBuzz(_ n: Int) -> [String] {
var ans = [String]()
for i in 1...n {
var s = ""
if i % 3 == 0 {
s += "Fizz"
}
if i % 5 == 0 {
s += "Buzz"
}
if i % 3 != 0 && i % 5 != 0 {
s += "\(i)"
}
ans.append(s)
}
return ans
}
}
|
mit
|
736045c11f4ebd17bba15544ff6cc1d1
| 14.631579 | 41 | 0.364865 | 2.446281 | false | false | false | false |
fgulan/letter-ml
|
project/LetterML/Frameworks/framework/Source/Operations/LevelsAdjustment.swift
|
9
|
1193
|
public class LevelsAdjustment: BasicOperation {
public var minimum:Color = Color(red:0.0, green:0.0, blue:0.0) { didSet { uniformSettings["levelMinimum"] = minimum } }
public var middle:Color = Color(red:1.0, green:1.0, blue:1.0) { didSet { uniformSettings["levelMiddle"] = middle } }
public var maximum:Color = Color(red:1.0, green:1.0, blue:1.0) { didSet { uniformSettings["levelMaximum"] = maximum } }
public var minOutput:Color = Color(red:0.0, green:0.0, blue:0.0) { didSet { uniformSettings["minOutput"] = minOutput } }
public var maxOutput:Color = Color(red:1.0, green:1.0, blue:1.0) { didSet { uniformSettings["maxOutput"] = maxOutput } }
// TODO: Is this an acceptable interface, or do I need to bring this closer to the old implementation?
public init() {
super.init(fragmentShader:LevelsFragmentShader, numberOfInputs:1)
({minimum = Color(red:0.0, green:0.0, blue:0.0)})()
({middle = Color(red:1.0, green:1.0, blue:1.0)})()
({maximum = Color(red:1.0, green:1.0, blue:1.0)})()
({minOutput = Color(red:0.0, green:0.0, blue:0.0)})()
({maxOutput = Color(red:1.0, green:1.0, blue:1.0)})()
}
}
|
mit
|
0a51b27bcb34defaa8eaaf3ffbb4b0f7
| 61.842105 | 124 | 0.637049 | 3.147757 | false | false | false | false |
smitshah14/CocoaPodDemoBlinkingLabel
|
Example/CocoaPodDemoBlinkingLabel/ViewController.swift
|
1
|
1416
|
//
// ViewController.swift
// CocoaPodDemoBlinkingLabel
//
// Created by SMIT V SHAH on 11/13/2015.
// Copyright (c) 2015 SMIT V SHAH. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var isBlinking = false
let blinkingLabel = BlinkingLabel(frame: CGRectMake(10, 20, 200, 30))
override func viewDidLoad() {
super.viewDidLoad()
// Setup the BlinkingLabel
blinkingLabel.text = "I blink!"
blinkingLabel.font = UIFont.systemFontOfSize(20)
view.addSubview(blinkingLabel)
blinkingLabel.startBlinking()
isBlinking = true
// Create a UIButton to toggle the blinking
let toggleButton = UIButton(frame: CGRectMake(10, 60, 125, 30))
toggleButton.setTitle("Toggle Blinking", forState: .Normal)
toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal)
toggleButton.addTarget(self, action: "toggleBlinking", forControlEvents: .TouchUpInside)
view.addSubview(toggleButton)
}
func toggleBlinking() {
if (isBlinking) {
blinkingLabel.stopBlinking()
} else {
blinkingLabel.startBlinking()
}
isBlinking = !isBlinking
}
}
|
mit
|
bdb83a261b29070c64a7597ac33af083
| 27.897959 | 96 | 0.642655 | 4.832765 | false | false | false | false |
JaySonGD/SwiftDayToDay
|
获取系统通信录1/获取系统通信录1/ViewController.swift
|
1
|
1763
|
//
// ViewController.swift
// 获取系统通信录1
//
// Created by czljcb on 16/3/18.
// Copyright © 2016年 lQ. All rights reserved.
//
import UIKit
import AddressBookUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let VC = ABPeoplePickerNavigationController()
VC.peoplePickerDelegate = self
presentViewController(VC, animated: true, completion: nil)
}
}
extension ViewController: ABPeoplePickerNavigationControllerDelegate{
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
print(person)
let name = (ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as! String) + (ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as! String)
let phones: ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef
let count = ABMultiValueGetCount(phones)
print(name)
for i in 0..<count {
print( ABMultiValueCopyLabelAtIndex(phones, i).takeRetainedValue())
print( ABMultiValueCopyValueAtIndex(phones, i).takeRetainedValue())
}
}
// func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) {
//
// print(person,property,identifier)
// }
}
|
mit
|
82de08f5a58803ff3049bc8a6ffd4ab1
| 33.254902 | 193 | 0.699885 | 5.181009 | false | false | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/GDPR.swift
|
2
|
5238
|
//
// GDPR.swift
// Neocom
//
// Created by Artem Shimanski on 18.05.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import AdSupport
import Alamofire
import Futures
//fileprivate let GDPRCountryCodes = [
// "BE", "EL", "LT", "PT",
// "BG", "ES", "LU", "RO",
// "CZ", "FR", "HU", "SI",
// "DK", "HR", "MT", "SK",
// "DE", "IT", "NL", "FI",
// "EE", "CY", "AT", "SE",
// "IE", "LV", "PL", "UK",
// "CH", "NO", "IS", "LI"
//]
//fileprivate let GDPRStartDate: Date = {
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy.MM.dd HH:mm"
// #if DEBUG
// return dateFormatter.date(from: "2018.05.20 00:00")!
// #else
// return dateFormatter.date(from: "2018.05.28 00:00")!
// #endif
//}()
struct IsEEA: Codable {
var is_request_in_eea_or_unknown: Bool
}
//struct APIIP: Codable {
// var country: String
// var countryCode: String
//}
extension UIStoryboard {
static let gdpr = UIStoryboard(name: "GDPR", bundle: nil)
}
class GDPR {
private static var window: UIWindow?
class func requireConsent() -> Future<Bool> {
// guard Date() >= GDPRStartDate else {return .init(false)}
let promise = Promise<Bool>()
Session.default.request("https://adservice.google.com/getconfig/pubvendors?es=2&pubs=ca-app-pub-0434787749004673~8578320061").validate().responseDecodable { (response: DataResponse<IsEEA>) in
switch response.result {
case let .success(value):
#if DEBUG
try? promise.fulfill(true)
#else
try? promise.fulfill(value.is_request_in_eea_or_unknown)
#endif
case let .failure(error):
try? promise.fail(error)
}
}
// Alamofire.request("http://ip-api.com/json").validate().responseJSONDecodable { (response: DataResponse<APIIP>) in
// switch response.result {
// case let .success(value):
// try? promise.fulfill(GDPRCountryCodes.contains(value.countryCode.uppercased()))
// case let .failure(error):
// try? promise.fail(error)
// }
// }
return promise.future
}
class func requestConsent() -> Future<Bool> {
guard ASIdentifierManager.shared().isAdvertisingTrackingEnabled else {return .init(false)}
let stored = UserDefaults.standard.object(forKey: UserDefaults.Key.NCConsent) as? NSNumber
return DispatchQueue.global(qos: .utility).async { () -> Future<Bool> in
guard try requireConsent().get() else {return (.init(true))}
#if DEBUG
#else
if let stored = stored {
return .init(stored.boolValue)
}
#endif
let message = try consentRequestMessage().get()
return DispatchQueue.main.async {
window = UIWindow(frame: UIScreen.main.bounds)
window?.windowLevel = UIWindowLevelNormal + 1
window?.backgroundColor = .clear
window?.rootViewController = UIViewController()
window?.rootViewController?.view.backgroundColor = .clear
window?.makeKeyAndVisible()
let controller = UIStoryboard.gdpr.instantiateInitialViewController()!
let promise = Promise<Bool>()
if let gdprController = ((controller as? UINavigationController)?.topViewController as? GDPRViewController){
gdprController.completionHandler = { hasConsent in
UserDefaults.standard.set(hasConsent, forKey: UserDefaults.Key.NCConsent)
window?.rootViewController?.dismiss(animated: true, completion: {
window?.isHidden = true
window = nil
try? promise.fulfill(hasConsent)
})
}
gdprController.text = message
}
window?.rootViewController?.present(controller, animated: true, completion: nil)
return promise.future
}
}
}
private class func consentRequestMessage() -> Future<NSAttributedString> {
let promise = Promise<NSAttributedString>()
Session.default.request("https://s3-us-west-1.amazonaws.com/appodeal-ios/docs/GDPRPrivacy.html").validate().responseString { response in
do {
switch response.result {
case let .success(string):
let data = string.replacingOccurrences(of: "%APP_NAME%", with: "Neocom").data(using: .utf8) ?? Data()
let s = try NSMutableAttributedString(data: data, options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
s.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: s.length))
try promise.fulfill(s)
case let .failure(error):
try? promise.fail(error)
}
}
catch {
try? promise.fail(error)
}
}
return promise.future
}
}
class GDPRViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var completionHandler: ((Bool) -> Void)?
var text: NSAttributedString?
override func viewDidLoad() {
super.viewDidLoad()
textView.attributedText = text
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func onOk(_ sender: Any) {
completionHandler?(true)
}
@IBAction func onCancel(_ sender: Any) {
completionHandler?(false)
}
}
extension GDPRViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if UIApplication.shared.canOpenURL(URL) {
UIApplication.shared.openURL(URL)
}
return false
}
}
|
lgpl-2.1
|
0f7f247c3a84eaac347a66c16776806e
| 27.774725 | 193 | 0.68818 | 3.484365 | false | false | false | false |
HongliYu/firefox-ios
|
Client/Frontend/AuthenticationManager/AppAuthenticator.swift
|
1
|
2539
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftKeychainWrapper
import LocalAuthentication
import Deferred
class AppAuthenticator {
static func presentAuthenticationUsingInfo(_ authenticationInfo: AuthenticationKeychainInfo, touchIDReason: String, success: (() -> Void)?, cancel: (() -> Void)?, fallback: (() -> Void)?) {
if authenticationInfo.useTouchID {
let localAuthContext = LAContext()
localAuthContext.localizedFallbackTitle = AuthenticationStrings.enterPasscode
localAuthContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: touchIDReason) { didSucceed, error in
if didSucceed {
// Update our authentication info's last validation timestamp so we don't ask again based
// on the set required interval
authenticationInfo.recordValidation()
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
DispatchQueue.main.async {
success?()
}
return
}
guard let authError = error,
let code = LAError.Code(rawValue: authError._code) else {
return
}
DispatchQueue.main.async {
switch code {
case .userFallback, .touchIDNotEnrolled, .touchIDNotAvailable, .touchIDLockout:
fallback?()
case .userCancel:
cancel?()
default:
cancel?()
}
}
}
} else {
fallback?()
}
}
static func presentPasscodeAuthentication(_ presentingNavController: UINavigationController?) -> Deferred<Bool> {
let deferred = Deferred<Bool>()
let passcodeVC = PasscodeEntryViewController(passcodeCompletion: { isOk in
deferred.fill(isOk)
})
let navController = UINavigationController(rootViewController: passcodeVC)
navController.modalPresentationStyle = .formSheet
presentingNavController?.present(navController, animated: true, completion: nil)
return deferred
}
}
|
mpl-2.0
|
988f878c4c964221997967eab7ffddc7
| 41.316667 | 193 | 0.594722 | 6.493606 | false | false | false | false |
adamwaite/AJWValidator
|
Validator/Sources/UIKit+Validator/ValidatableInterfaceElement.swift
|
3
|
2601
|
import Foundation
import ObjectiveC
public protocol ValidatableInterfaceElement {
associatedtype InputType: Validatable
var inputValue: InputType? { get }
func validate<R: ValidationRule>(rule r: R) -> ValidationResult
func validate(rules: ValidationRuleSet<InputType>) -> ValidationResult
var validationHandler: ((ValidationResult) -> Void)? { get set }
func validateOnInputChange(enabled: Bool)
}
private var ValidatableInterfaceElementRulesKey: UInt8 = 0
private var ValidatableInterfaceElementHandlerKey: UInt8 = 0
extension ValidatableInterfaceElement {
public func validate<Rule: ValidationRule>(rule: Rule) -> ValidationResult {
guard let value = inputValue as? Rule.InputType else {
return .invalid([rule.error])
}
let result = Validator.validate(input: value, rule: rule)
validationHandler?(result)
return result
}
public func validate(rules: ValidationRuleSet<InputType>) -> ValidationResult {
let result = Validator.validate(input: inputValue, rules: rules)
validationHandler?(result)
return result
}
@discardableResult
public func validate() -> ValidationResult {
guard let attachedRules = validationRules else {
#if DEBUG
print("Validator Error: attempted to validate without attaching rules")
#endif
return .valid
}
return validate(rules: attachedRules)
}
public var validationRules: ValidationRuleSet<InputType>? {
get {
return objc_getAssociatedObject(self, &ValidatableInterfaceElementRulesKey) as? ValidationRuleSet<InputType>
}
set(newValue) {
if let n = newValue {
objc_setAssociatedObject(self, &ValidatableInterfaceElementRulesKey, n as AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
public var validationHandler: ((ValidationResult) -> Void)? {
get {
return objc_getAssociatedObject(self, &ValidatableInterfaceElementHandlerKey) as? (ValidationResult) -> Void
}
set(newValue) {
if let n = newValue {
objc_setAssociatedObject(self, &ValidatableInterfaceElementHandlerKey, n as AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
|
mit
|
fcc543f6a1e24d6b4a0c7b044848b1c8
| 29.244186 | 160 | 0.620146 | 5.617711 | false | false | false | false |
vnu/YelpMe
|
YelpMe/HTTPClient.swift
|
1
|
2832
|
//
// HTTPClient.swift
// YelpMe
//
// Created by Vinu Charanya on 2/10/16.
// Copyright © 2016 vnu. All rights reserved.
//
let yelpConsumerKey = "3O_QAfnr7VV-oLljo6KiBQ"
let yelpConsumerSecret = "qv6Rro07E2zmfHFbYZhd64TCbfc"
let yelpToken = "SjEmNlPN7uWIE0-3aGUMIt2rCa2cZPTm"
let yelpTokenSecret = "4hpfPdbzhv0rVK6SdCOvGDSLkOg"
import AFNetworking
import BDBOAuth1Manager
import UIKit
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
}
class HTTPClient: BDBOAuth1RequestOperationManager{
var accessToken:String!
var accessSecret:String!
let yelpBaseURL = "https://api.yelp.com/v2/"
init() {
self.accessToken = yelpToken
self.accessSecret = yelpTokenSecret
let baseUrl = NSURL(string: self.yelpBaseURL)
super.init(baseURL: baseUrl, consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret);
let token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(term, sort: nil, categories: nil, deals: nil, distance: nil, completion: completion)
}
func searchWithTerm(term: String, sort: String?, categories: [String]?, deals: Bool?, distance: String?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term, "ll": "37.785771,-122.406165"]
print("distnce: \(distance)")
if sort != nil {
parameters["sort"] = sort
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = (categories!).joinWithSeparator(",")
}
if deals != nil {
parameters["deals_filter"] = deals!
}
if distance != nil{
parameters["radius_filter"] = distance!
}
print(parameters)
return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
let dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}, failure: { (operation: AFHTTPRequestOperation?, error: NSError!) -> Void in
completion(nil, error)
})!
}
}
|
apache-2.0
|
f981de69cff11d9d2a52300f8f546fa6
| 33.108434 | 181 | 0.630872 | 4.244378 | false | false | false | false |
alblue/swift
|
stdlib/public/SDK/Intents/INParameter.swift
|
19
|
931
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
@available(iOS 11.0, watchOS 4.0, *)
extension INParameter {
@nonobjc
public convenience init?<Root, Value>(keyPath: KeyPath<Root, Value>) {
if let aClass = Root.self as? AnyClass, let keyPathString = keyPath._kvcKeyPathString {
self.init(for: aClass, keyPath: keyPathString)
} else {
return nil
}
}
}
#endif
|
apache-2.0
|
31d448f49c312be9772287b5b1242e38
| 32.25 | 91 | 0.586466 | 4.586207 | false | false | false | false |
nakau1/NerobluCore
|
NerobluCore/NBNumber.swift
|
1
|
2309
|
// =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - Intの拡張 -
public extension Int {
/// 指定した範囲の中から乱数を取得する
///
/// 最小値は0を下回ってはいけません。また、最小値は最大値を上回ってはいけません
/// - parameter min: 最小値
/// - parameter max: 最大値
/// - returns: 乱数
public static func random(min min: Int, max: Int) -> Int {
let minn = min < 0 ? 0 : min
let maxn = max + 1
let x = UInt32(maxn < minn ? 0 : maxn - minn)
let r = Int(arc4random_uniform(x))
return minn + r
}
/// 金額表示用の文字列
///
/// 使用例
/// (12000).currency // "12,000"
public var currency: String {
let fmt = NSNumberFormatter()
fmt.numberStyle = .DecimalStyle
fmt.groupingSeparator = ","
fmt.groupingSize = 3
return fmt.stringFromNumber(self) ?? ""
}
/// CGFloatにキャストした値
public var f: CGFloat { return CGFloat(self) }
/// 文字列にキャストした値
public var string: String { return "\(self)" }
}
// MARK: - Floatの拡張 -
public extension Float {
/// CGFloatにキャストした値
public var f: CGFloat { return CGFloat(self) }
/// 文字列にキャストした値
public var string: String { return "\(self)" }
}
// MARK: - Doubleの拡張 -
public extension Double {
/// CGFloatにキャストした値
public var f: CGFloat { return CGFloat(self) }
/// 文字列にキャストした値
public var string: String { return "\(self)" }
}
// MARK: - CGFloat拡張 -
public extension CGFloat {
/// Intにキャストした値
public var int: Int { return Int(self) }
/// Floatにキャストした値
public var float: Float { return Float(self) }
/// Doubleにキャストした値
public var double: Double { return Double(self) }
/// 文字列にキャストした値
public var string: String { return "\(self)" }
}
|
apache-2.0
|
2582b3517fff06a27e7ad7401f943935
| 24.064103 | 80 | 0.524297 | 3.647388 | false | false | false | false |
gregomni/swift
|
validation-test/Sema/SwiftUI/rdar76252310.swift
|
2
|
2171
|
// RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.15 -swift-version 5
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
import SwiftUI
class Visibility: ObservableObject { // expected-note 2{{class 'Visibility' does not conform to the 'Sendable' protocol}}
@Published var yes = false // some nonsense
}
struct CoffeeTrackerView: View { // expected-note{{consider making struct 'CoffeeTrackerView' conform to the 'Sendable' protocol}}
@ObservedObject var showDrinkList: Visibility = Visibility()
var storage: Visibility = Visibility()
var body: some View {
VStack {
Button(action: {}) {
Image(self.showDrinkList.yes ? "add-coffee" : "add-tea")
.renderingMode(.template)
}
}
}
}
@MainActor
func fromMainActor() async {
let view = CoffeeTrackerView()
_ = view.body
_ = view.showDrinkList
_ = view.storage
}
func fromConcurrencyAware() async {
// expected-note@+3 {{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+2 {{expression is 'async' but is not marked with 'await'}}
// expected-warning@+1 {{non-sendable type 'CoffeeTrackerView' returned by call to main actor-isolated function cannot cross actor boundary}}
let view = CoffeeTrackerView()
// expected-note@+3 {{property access is 'async'}}
// expected-warning@+2 {{non-sendable type 'some View' in implicitly asynchronous access to main actor-isolated property 'body' cannot cross actor boundary}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
_ = view.body
// expected-note@+3 {{property access is 'async'}}
// expected-warning@+2 {{non-sendable type 'Visibility' in implicitly asynchronous access to main actor-isolated property 'showDrinkList' cannot cross actor boundary}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
_ = view.showDrinkList
_ = await view.storage // expected-warning {{non-sendable type 'Visibility' in implicitly asynchronous access to main actor-isolated property 'storage' cannot cross actor boundary}}
}
|
apache-2.0
|
91cc2f834b0c878c455cc9770fa9ee8b
| 39.962264 | 183 | 0.703363 | 4.199226 | false | false | false | false |
jianwoo/WordPress-iOS
|
WordPress/Classes/ViewRelated/Notifications/Style/WPStyleGuide+Notifications.swift
|
1
|
10371
|
import Foundation
extension WPStyleGuide
{
public struct Notifications
{
// MARK: - Styles Used by NotificationsViewController
//
// NoteTableViewCell
public static let noticonFont = UIFont(name: "Noticons", size: 16)
public static let noticonTextColor = UIColor.whiteColor()
public static let noticonReadColor = UIColor(red: 0xA4/255.0, green: 0xB9/255.0, blue: 0xC9/255.0, alpha: 0xFF/255.0)
public static let noticonUnreadColor = UIColor(red: 0x25/255.0, green: 0x9C/255.0, blue: 0xCF/255.0, alpha: 0xFF/255.0)
public static let noticonUnmoderatedColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0)
public static let noteBackgroundReadColor = UIColor.whiteColor()
public static let noteBackgroundUnreadColor = UIColor(red: 0xF1/255.0, green: 0xF6/255.0, blue: 0xF9/255.0, alpha: 0xFF/255.0)
public static let noteSeparatorColor = blockSeparatorColor
public static let gravatarPlaceholderImage = UIImage(named: "gravatar")
// Subject Text
public static let subjectRegularStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectRegularFont,
NSForegroundColorAttributeName: subjectTextColor ]
public static let subjectBoldStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectBoldFont ]
public static let subjectItalicsStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectItalicsFont ]
public static let subjectNoticonStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectNoticonFont!,
NSForegroundColorAttributeName: subjectNoticonColor ]
// Subject Snippet
private static let snippetColor = WPStyleGuide.allTAllShadeGrey()
public static let snippetRegularStyle = [ NSParagraphStyleAttributeName: snippetParagraph,
NSFontAttributeName: subjectRegularFont,
NSForegroundColorAttributeName: snippetColor ]
// MARK: - Styles used by NotificationDetailsViewController
//
// Header
public static let headerFont = WPFontManager.openSansBoldFontOfSize(headerFontSize)
public static let headerTextColor = UIColor(red: 0xA7/255.0, green: 0xBB/255.0, blue: 0xCA/255.0, alpha: 0xFF/255.0)
public static let headerBackgroundColor = UIColor(red: 0xFF/255.0, green: 0xFF/255.0, blue: 0xFF/255.0, alpha: 0xEA/255.0)
public static let headerRegularStyle = [ NSParagraphStyleAttributeName: headerParagraph,
NSFontAttributeName: headerFont,
NSForegroundColorAttributeName: headerTextColor ]
// Blocks
public static let blockRegularFont = WPFontManager.openSansRegularFontOfSize(blockFontSize)
public static let blockBoldFont = WPFontManager.openSansBoldFontOfSize(blockFontSize)
public static let blockItalicsFont = WPFontManager.openSansItalicFontOfSize(blockFontSize)
public static let blockTextColor = WPStyleGuide.littleEddieGrey()
public static let blockQuotedColor = UIColor(red: 0x7E/255.0, green: 0x9E/255.0, blue: 0xB5/255.0, alpha: 0xFF/255.0)
public static let blockBackgroundColor = UIColor.whiteColor()
public static let blockLinkColor = WPStyleGuide.baseLighterBlue()
public static let blockSubtitleColor = WPStyleGuide.baseDarkerBlue()
public static let blockSeparatorColor = WPStyleGuide.readGrey()
public static let blockUnapprovedSideColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0)
public static let blockUnapprovedBgColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0x19/255.0)
public static let blockUnapprovedTextColor = UIColor(red: 0xF0/255.0, green: 0x82/255.0, blue: 0x1E/255.0, alpha: 0xFF/255.0)
public static let blockRegularStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: blockTextColor]
public static let blockBoldStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockBoldFont,
NSForegroundColorAttributeName: blockTextColor]
public static let blockItalicsStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockItalicsFont,
NSForegroundColorAttributeName: blockTextColor]
public static let blockQuotedStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockItalicsFont,
NSForegroundColorAttributeName: blockQuotedColor]
public static let blockBadgeStyle = [ NSParagraphStyleAttributeName: badgeParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: blockTextColor]
// Badges
public static let badgeBackgroundColor = UIColor.clearColor()
// Action Buttons
public static let blockActionDisabledColor = UIColor(red: 0x7F/255.0, green: 0x9E/255.0, blue: 0xB4/255.0, alpha: 0xFF/255.0)
public static let blockActionEnabledColor = UIColor(red: 0xEA/255.0, green: 0x6D/255.0, blue: 0x1B/255.0, alpha: 0xFF/255.0)
// RichText Helpers
public static func blockBackgroundColorForRichText(isBadge: Bool) -> UIColor {
return isBadge ? badgeBackgroundColor : blockBackgroundColor
}
// Comment Helpers
public static func blockTextColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockTextColor : blockUnapprovedTextColor
}
public static func blockTimestampColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockQuotedColor : blockUnapprovedTextColor
}
public static func blockLinkColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockLinkColor : blockUnapprovedTextColor
}
// MARK: - Constants
//
public static let headerFontSize = CGFloat(12)
public static let headerLineSize = CGFloat(16)
public static let subjectFontSize = UIDevice.isPad() ? CGFloat(16) : CGFloat(14)
public static let subjectNoticonSize = UIDevice.isPad() ? CGFloat(15) : CGFloat(14)
public static let subjectLineSize = UIDevice.isPad() ? CGFloat(24) : CGFloat(18)
public static let snippetLineSize = subjectLineSize
public static let blockFontSize = UIDevice.isPad() ? CGFloat(16) : CGFloat(14)
public static let blockLineSize = UIDevice.isPad() ? CGFloat(24) : CGFloat(20)
public static let maximumCellWidth = CGFloat(600)
// MARK: - Private Propreties
//
// ParagraphStyle's
private static let headerParagraph = NSMutableParagraphStyle(
minLineHeight: headerLineSize, maxLineHeight: headerLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let subjectParagraph = NSMutableParagraphStyle(
minLineHeight: subjectLineSize, maxLineHeight: subjectLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let snippetParagraph = NSMutableParagraphStyle(
minLineHeight: snippetLineSize, maxLineHeight: snippetLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let blockParagraph = NSMutableParagraphStyle(
minLineHeight: blockLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let badgeParagraph = NSMutableParagraphStyle(
minLineHeight: blockLineSize, maxLineHeight: blockLineSize, lineBreakMode: .ByWordWrapping, alignment: .Center
)
// Colors
private static let subjectTextColor = WPStyleGuide.littleEddieGrey()
private static let subjectNoticonColor = noticonReadColor
// Fonts
private static let subjectRegularFont = WPFontManager.openSansRegularFontOfSize(subjectFontSize)
private static let subjectBoldFont = WPFontManager.openSansBoldFontOfSize(subjectFontSize)
private static let subjectItalicsFont = WPFontManager.openSansItalicFontOfSize(subjectFontSize)
private static let subjectNoticonFont = UIFont(name: "Noticons", size: subjectNoticonSize)
}
// MARK: - ObjectiveC Helpers: Nuke me once NotificationDetailsViewController is Swifted!
public class func notificationsBlockSeparatorColor() -> UIColor {
return Notifications.blockSeparatorColor
}
}
|
gpl-2.0
|
9aea84ac6d087844a87d793860b7aca2
| 60.366864 | 134 | 0.605438 | 5.879252 | false | false | false | false |
hongsign/swift-customUI
|
SudokuGenerator.swift
|
1
|
28466
|
//
// SudokuGenerator.swift
// Dev
//
// Created by YU HONG on 2016-11-30.
// Copyright © 2016 homesoft. All rights reserved.
//
import Foundation
class SudokuGenerator {
/**
* Indicator if generation should
* start from randomly generated board.
*/
//public static final char PARAM_GEN_RND_BOARD = '1';
/**
* Indicator showing that initial board should be solved
* before generation process will be started.
*/
//public static final char PARAM_DO_NOT_SOLVE = '2';
/**
* Indicator showing that initial board should not be
* randomly transformed before generation process will be started.
*/
//public static final char PARAM_DO_NOT_TRANSFORM = '3';
/**
* Indicator if generation should
* start from randomly generated board.
*/
private var generateRandomBoard: Bool = false
/**
* Indicator showing that initial board should not be
* randomly transformed before generation process will be started.
*/
private var transformBeforeGeneration: Bool = false
/**
* Indicator showing that initial board should be solved
* before generation process will be started.
*/
private var solveBeforeGeneration: Bool = false
/**
* Board size derived form SudokuBoard class.
*/
//private static final int BOARD_SIZE = SudokuBoard.BOARD_SIZE;
private let BOARD_SIZE: Int = 9
/**
* Board cells number derived form SudokuBoard class.
*/
//private static final int BOARD_CELLS_NUMBER = SudokuBoard.BOARD_CELLS_NUMBER;
private let BOARD_CELLS_NUMBER: Int = 81
/**
* Empty cell identifier.
*/
//private static final int CELL_EMPTY = BoardCell.EMPTY;
let CELL_EMPTY: Int = SudokuBoardCell.EMPTY
/**
* Marker if analyzed digit 0...9 is still not used.
*/
//private static final int DIGIT_STILL_FREE = BoardCell.DIGIT_STILL_FREE;
let DIGIT_STILL_FREE: Int = SudokuBoardCell.DIGIT_STILL_FREE
/**
* Digit 0...9 can not be used in that place.
*/
//private static final int DIGIT_IN_USE = BoardCell.DIGIT_IN_USE;
let DIGIT_IN_USE: Int = SudokuBoardCell.DIGIT_IN_USE
/**
* If yes then filled cells with the same impact will be randomized.
*/
private var randomizeFilledCells: Bool = false
/**
* Initial board that will be a basis for
* the generation process
*/
//private int[][] sudokuBoard;
var sudokuBoard: [[Int]]?
/**
* Board cells array
*/
//private BoardCell[] boardCells;
var boardCells: [SudokuBoardCell]?
/**
* Message type normal.
*/
//private static final int MSG_INFO = 1;
let MSG_INFO: Int = 1
/**
* Message type error.
*/
//private static final int MSG_ERROR = -1;
let MSG_ERROR: Int = -1
/**
* Message from the solver.
*/
//private String messages = "";
var messages: String = ""
/**
* Last message.
*/
//private String lastMessage = "";
var lastMessage: String = ""
/**
* Last error message.
*/
//private String lastErrorMessage = "";
var lastErrorMessage: String = ""
/**
* Solving time in seconds.
*/
//private double computingTime;
var computingTime: Double = 0
/**
* Generator state.
*
* @see #GENERATOR_INIT_STARTED
* @see #GENERATOR_INIT_FINISHED
* @see #GENERATOR_INIT_FAILED
* @see #GENERATOR_GEN_NOT_STARTED
* @see #GENERATOR_GEN_STARTED
* @see #GENERATOR_GEN_STARTED
* @see #GENERATOR_GEN_FAILED
*/
//private int generatorState;
var generatorState: Int = 0
/**
* Generator init started
* @see #getGeneratorState()
*/
//public static final int GENERATOR_INIT_STARTED = 1;
let GENERATOR_INIT_STARTED: Int = 1
/**
* Generator init finished.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_INIT_FINISHED = 2;
let GENERATOR_INIT_FINISHED: Int = 2
/**
* Generator init failed.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_INIT_FAILED = -1;
let GENERATOR_INIT_FAILED: Int = -1
/**
* Generation process not started.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_GEN_NOT_STARTED = -2;
let GENERATOR_GEN_NOT_STARTED: Int = -2
/**
* Generation process started.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_GEN_STARTED = 3;
let GENERATOR_GEN_STARTED: Int = 3
/**
* Generation process finished.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_GEN_FINISHED = 4;
let GENERATOR_GEN_FINISHED: Int = 4
/**
* Generation process failed.
* @see #getGeneratorState()
*/
//public static final int GENERATOR_GEN_FAILED = -3;
let GENERATOR_GEN_FAILED: Int = -3
/**
* Internal variables init for constructor.
*/
private func initIntervalVars() {
generatorState = GENERATOR_INIT_STARTED
randomizeFilledCells = true
computingTime = 0
}
/**
* Set parameters provided by the user.
*
* @param parameters parameters list
* @see #PARAM_GEN_RND_BOARD
* @see #PARAM_DO_NOT_SOLVE
*/
private func setParameters(generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
let randomboard = generaterandomboard ?? false
let solve = solvebeforegeneration ?? true
let transform = transformbeforegeneration ?? true
generateRandomBoard = randomboard
solveBeforeGeneration = solve
transformBeforeGeneration = transform
}
/**
* Board initialization method.
* @param initBoard Initial board.
* @param info The string to pass to the msg builder.
*/
private func boardInit(initBoard: [[Int]]?, info: String) {
var puzzle: SudokuSolver?
guard let board = initBoard else {
if generateRandomBoard {
puzzle = SudokuSolver(sudokuBoard: SudokuPuzzles.PUZZLE_EMPTY)
puzzle!.solve()
if (puzzle!.getSolvingState() == SudokuSolver.SOLVING_STATE_SOLVED) {
sudokuBoard = puzzle!.solvedBoard
addMessage("(SudokuGenerator) Generator initialized using random board (" + info + ").", msgType: MSG_INFO)
generatorState = GENERATOR_INIT_FINISHED
return
} else {
addMessage("(SudokuGenerator) Generator initialization using random board (" + info + ") failed. Board with error?", msgType: MSG_ERROR)
addMessage(puzzle!.getLastErrorMessage(), msgType: MSG_ERROR)
generatorState = GENERATOR_INIT_FAILED
return
}
}
return
}
if (SudokuStore.checkPuzzle(board) == false) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator initialization (" + info + ") failed. Board with error?", msgType: MSG_ERROR)
return
}
if (solveBeforeGeneration == true) {
puzzle = SudokuSolver(sudokuBoard: board)
puzzle!.solve()
if (puzzle!.getSolvingState() == SudokuSolver.SOLVING_STATE_SOLVED) {
sudokuBoard = puzzle!.solvedBoard
addMessage("(SudokuGenerator) Generator initialized usign provided board + finding solution (" + info + ").", msgType: MSG_INFO)
generatorState = GENERATOR_INIT_FINISHED
return
} else {
addMessage("(SudokuGenerator) Generator initialization usign provided board + finding solution (" + info + ") failed. Board with error?", msgType: MSG_ERROR)
addMessage(puzzle!.getLastErrorMessage(),msgType: MSG_ERROR)
generatorState = GENERATOR_INIT_FAILED
return
}
}
puzzle = SudokuSolver(sudokuBoard: board)
if (puzzle!.checkIfUniqueSolution() == SudokuSolver.SOLUTION_UNIQUE) {
sudokuBoard = board
addMessage("(SudokuGenerator) Generator initialized usign provided board (" + info + ").", msgType: MSG_INFO)
generatorState = GENERATOR_INIT_FINISHED
return
} else {
addMessage("(SudokuGenerator) Generator initialization usign provided board (" + info + ") failed. Solution not exists or is non unique.", msgType: MSG_ERROR)
addMessage(puzzle!.getLastErrorMessage(), msgType: MSG_ERROR)
generatorState = GENERATOR_INIT_FAILED
return
}
}
/**
* Default constructor based on random Sudoku puzzle example.
*
* @param parameters Optional parameters.
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*/
init(generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
setParameters(generaterandomboard, solvebeforegeneration: solvebeforegeneration, transformbeforegeneration: transformbeforegeneration)
initIntervalVars()
//var b: [[Int]]?
if (generateRandomBoard == true) {
boardInit(nil, info: "random board")
} else {
let example = SudokuStore.randomIndex( SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES )
let board = SudokuStore.boardCopy( SudokuStore.getPuzzleExample(example) )
if (transformBeforeGeneration == true) {
boardInit(SudokuStore.seqOfRandomBoardTransf(board), info: "transformed example: " + String(example))
}
else {
boardInit(board, info: "example: " + String(example))
}
}
}
/**
* Default constructor based on puzzle example.
*
* @param example Example number between 0 and {@link SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES}.
* @param parameters Optional parameters.
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*/
init(example: Int, generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
setParameters(generaterandomboard, solvebeforegeneration: solvebeforegeneration, transformbeforegeneration: transformbeforegeneration)
initIntervalVars()
if ( (example >= 0) && (example < SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES) ) {
let board: [[Int]] = SudokuStore.boardCopy( SudokuStore.getPuzzleExample(example) )
if (transformBeforeGeneration == true) {
boardInit(SudokuStore.seqOfRandomBoardTransf(board)!, info: "transformed example: " + String(example))
}
else {
boardInit(board, info: "example: " + String(example))
}
}
else {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized incorrect example number: " + String(example) + " - should be between 1 and " + String(SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES) + ".", msgType: MSG_ERROR)
}
}
/**
* Default constructor based on provided initial board.
*
* @param initialBoard Array with the board definition.
* @param parameters Optional parameters
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*/
init(initialBoard: [[Int]]?, generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
setParameters(generaterandomboard, solvebeforegeneration: solvebeforegeneration, transformbeforegeneration: transformbeforegeneration)
initIntervalVars()
guard let board = initialBoard else {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - null initial board.", msgType: MSG_ERROR)
return
}
if (board.count != BOARD_SIZE) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - incorrect number of rows in initial board, is: " + String(board.count) + ", expected: " + String(BOARD_SIZE) + ".", msgType: MSG_ERROR)
} else if (board[0].count != BOARD_SIZE) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - incorrect number of columns in initial board, is: " + String(board[0].count) + ", expected: " + String(BOARD_SIZE) + ".", msgType: MSG_ERROR)
} else if (SudokuStore.checkPuzzle(board) == false) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - initial board contains an error.", msgType: MSG_ERROR)
} else {
let b:[[Int]] = SudokuStore.boardCopy(board)
if (transformBeforeGeneration == true) {
boardInit( SudokuStore.seqOfRandomBoardTransf(b)!, info: "transformed board provided by the user")
}
else {
boardInit(b, info: "board provided by the user")
}
}
}
/**
* Constructor based on the sudoku board
* provided in text file.
*
* @param boardFilePath Path to the board definition.
* @param parameters Optional parameters
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*/
init(boardFilePath: String?, generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
setParameters(generaterandomboard, solvebeforegeneration: solvebeforegeneration, transformbeforegeneration: transformbeforegeneration)
initIntervalVars()
guard let path = boardFilePath else {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - null board file path.", msgType: MSG_ERROR)
return
}
if (path.characters.count == 0) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - blank board file path.", msgType: MSG_ERROR)
}
else {
let board = SudokuStore.loadBoard(path)
if (transformBeforeGeneration == true) {
boardInit( SudokuStore.seqOfRandomBoardTransf(board)!, info: "transformed board provided by the user")
}
else {
boardInit(board!,info: "board provided by the user")
}
}
}
/**
* Constructor based on the sudoku board
* provided array of strings.
*
* @param boardDefinition Board definition as array of strings
* (each array entry as separate row).
* @param parameters Optional parameters
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*
func SudokuGenerator(String[] boardDefinition, char... parameters) {
setParameters(parameters);
initInternalVars();
if (boardDefinition == null) {
generatorState = GENERATOR_INIT_FAILED;
addMessage("(SudokuGenerator) Generator not initialized - null board definition.", MSG_ERROR);
} else if (boardDefinition.length == 0) {
generatorState = GENERATOR_INIT_FAILED;
addMessage("(SudokuGenerator) Generator not initialized - blank board definition.", MSG_ERROR);
} else {
int[][] board = SudokuStore.loadBoard(boardDefinition);
if (transformBeforeGeneration == true)
boardInit( SudokuStore.seqOfRandomBoardTransf(board), "transformed board provided by the user");
else
boardInit(board, "board provided by the user");
}
}
*/
/**
* Constructor based on the sudoku board
* provided list of strings.
*
* @param boardDefinition Board definition as list of strings
* (each list entry as separate row).
* @param parameters Optional parameters
*
* @see #PARAM_DO_NOT_SOLVE
* @see #PARAM_DO_NOT_TRANSFORM
* @see #PARAM_GEN_RND_BOARD
*/
init(boardDefinition: Array<String>?, generaterandomboard: Bool?=false, solvebeforegeneration: Bool?=true, transformbeforegeneration: Bool?=true) {
setParameters(generaterandomboard, solvebeforegeneration: solvebeforegeneration, transformbeforegeneration: transformbeforegeneration)
initIntervalVars()
guard let bd = boardDefinition else {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - null board definition.", msgType: MSG_ERROR)
return
}
if (bd.count == 0) {
generatorState = GENERATOR_INIT_FAILED
addMessage("(SudokuGenerator) Generator not initialized - blank board definition.", msgType: MSG_ERROR)
}
else {
let board = SudokuStore.loadBoard(bd)
if (transformBeforeGeneration == true) {
boardInit( SudokuStore.seqOfRandomBoardTransf(board)!, info: "transformed board provided by the user")
}
else {
boardInit(board, info: "board provided by the user")
}
}
}
/**
* Sudoku puzzle generator.
*
* @return Sudoku puzzle if process finished correctly, otherwise null.
*/
func generate() -> [[Int]]? {
if (generatorState != GENERATOR_INIT_FINISHED) {
generatorState = GENERATOR_GEN_NOT_STARTED
addMessage("(SudokuGenerator) Generation process not started due to incorrect initialization.", msgType: MSG_ERROR)
return nil
}
let solvingStartTime = SudokuUtils.CurrentTimeMills()
generatorState = GENERATOR_GEN_STARTED
addMessage("(SudokuGenerator) Generation process started.", msgType: MSG_INFO);
if randomizeFilledCells {
addMessage("(SudokuGenerator) >>> Will randomize filled cells within cells with the same impact.", msgType: MSG_INFO)
}
boardCells = [SudokuBoardCell](count: BOARD_CELLS_NUMBER, repeatedValue: SudokuBoardCell())
var cellIndex = 0
for i in 0..<BOARD_SIZE {
for j in 0..<BOARD_SIZE {
let d = sudokuBoard?[i][j]
if (d != CELL_EMPTY) {
boardCells![cellIndex].set(i,colIndex: j,digit: d!)
cellIndex += 1
}
}
}
var filledCells = cellIndex
for i in 0..<BOARD_SIZE {
for j in 0..<BOARD_SIZE {
let d = sudokuBoard?[i][j]
if (d == CELL_EMPTY) {
boardCells![cellIndex].set(i, colIndex: j, digit: d!)
cellIndex += 1
}
}
}
updateDigitsStillFreeCounts()
sortBoardCells(0,r: filledCells-1)
repeat {
let r = 0
let i = boardCells![r].rowIndex
let j = boardCells![r].colIndex
let d = sudokuBoard![i][j]
sudokuBoard![i][j] = CELL_EMPTY
let s = SudokuSolver(sudokuBoard: sudokuBoard!)
if (s.checkIfUniqueSolution() != SudokuSolver.SOLUTION_UNIQUE) {
sudokuBoard![i][j] = d
}
let lastIndex = filledCells-1
if (r < lastIndex) {
let b1 = boardCells![r]
let b2 = boardCells![lastIndex]
boardCells![lastIndex] = b1
boardCells![r] = b2
}
filledCells -= 1
updateDigitsStillFreeCounts()
if (filledCells > 0) { sortBoardCells(0,r: filledCells-1) }
} while (filledCells > 0)
let solvingEndTime = SudokuUtils.CurrentTimeMills()
computingTime = Double(solvingEndTime - solvingStartTime) / 1000.0
generatorState = GENERATOR_GEN_FINISHED
addMessage("(SudokuGenerator) Generation process finished, computing time: " + String(computingTime) + " s.", msgType: MSG_INFO)
return sudokuBoard
}
/**
* Saves board to the text file.
*
* @param filePath Path to the file.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#saveBoard(int[][], String)
* @see SudokuStore#boardToString(int[][])
*/
func saveBoard(filePath: String) -> Bool {
let savingStatus = SudokuStore.saveBoard(sudokuBoard!, filePath: filePath)
if savingStatus {
addMessage("(saveBoard) Saving successful, file: " + filePath, msgType: MSG_INFO)
}
else {
addMessage("(saveBoard) Saving failed, file: " + filePath, msgType: MSG_ERROR)
}
return savingStatus;
}
/**
* Saves board to the text file.
*
* @param filePath Path to the file.
* @param headComment Comment to be added at the head.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#saveBoard(int[][], String, String)
* @see SudokuStore#boardToString(int[][], String)
*/
func saveBoard(filePath: String, headComment: String) -> Bool {
let savingStatus = SudokuStore.saveBoard(sudokuBoard!, filePath: filePath, headComment: headComment)
if savingStatus {
addMessage("(saveBoard) Saving successful, file: " + filePath, msgType: MSG_INFO)
}
else {
addMessage("(saveBoard) Saving failed, file: " + filePath, msgType: MSG_ERROR)
}
return savingStatus;
}
/**
* Saves board to the text file.
*
* @param filePath Path to the file.
* @param headComment Comment to be added at the head.
* @param tailComment Comment to be added at the tail.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#saveBoard(int[][], String, String, String)
* @see SudokuStore#boardToString(int[][], String, String)
*/
func saveBoard(filePath: String, headComment: String, tailComment: String) -> Bool {
let savingStatus = SudokuStore.saveBoard(sudokuBoard!, filePath: filePath, headComment: headComment, tailComment: tailComment)
if savingStatus {
addMessage("(saveBoard) Saving successful, file: " + filePath, msgType: MSG_INFO)
}
else {
addMessage("(saveBoard) Saving failed, file: " + filePath, msgType: MSG_ERROR)
}
return savingStatus;
}
/**
* Updating digits still free for a specific cell
* while generating process.
*/
private func updateDigitsStillFreeCounts() {
for i in 0..<BOARD_CELLS_NUMBER {
countDigitsStillFree((boardCells?[i])!)
}
}
/**
* Counts number of digits still free
* for a specific cell.
*
* @param boardCell
*/
private func countDigitsStillFree(boardCell: SudokuBoardCell) {
var digitsStillFree : [Int] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
var emptyCellsNumber: Int = 0
for j in 0..<BOARD_SIZE {
let boardDigit = sudokuBoard?[boardCell.rowIndex][j]
if boardDigit != CELL_EMPTY {
digitsStillFree[boardDigit!] = DIGIT_IN_USE
}
else {
if j != boardCell.colIndex {
emptyCellsNumber += 1
}
}
}
for i in 0..<BOARD_SIZE {
let boardDigit = sudokuBoard?[i][boardCell.colIndex]
if boardDigit != CELL_EMPTY {
digitsStillFree[boardDigit!] = DIGIT_IN_USE
}
else {
if i != boardCell.rowIndex {
emptyCellsNumber += 1
}
}
}
let sub: SubSquare = SubSquare.getSubSqare(boardCell)
/*
* Mark digits used in a sub-square.
*/
for i in sub.rowMin..<sub.rowMax {
for j in sub.colMin..<sub.colMax {
let boardDigit = sudokuBoard?[i][j]
if boardDigit != CELL_EMPTY {
digitsStillFree[boardDigit!] = DIGIT_IN_USE
}
else if ((i != boardCell.rowIndex) && (j != boardCell.colIndex)) {
emptyCellsNumber += 1
}
}
}
/*
* Find number of still free digits to use.
*/
digitsStillFree[boardCell.digit] = 0
boardCell.digitsStillFreeNumber = emptyCellsNumber
for digit in 1..<10 {
if (digitsStillFree[digit] == DIGIT_STILL_FREE) {
boardCell.digitsStillFreeNumber += 1
}
}
}
/**
* Sorting board cells
* @param l First index
* @param r Last index
*/
private func sortBoardCells(l: Int, r: Int) {
var i = l
var j = r
var x : SudokuBoardCell?
var w : SudokuBoardCell?
x = boardCells?[(l+r)/2]
repeat {
if randomizeFilledCells {
/*
* Adding randomization
*/
while ( boardCells?[i].orderPlusRndSeed() < x?.orderPlusRndSeed() ) { i += 1 }
while ( boardCells?[j].orderPlusRndSeed() > x?.orderPlusRndSeed() ) { j -= 1 }
}
else {
/*
* No randomization
*/
while ( boardCells?[i].order() < x?.order() ) { i += 1 }
while ( boardCells?[j].order() > x?.order() ) { j -= 1 }
}
if (i<=j) {
w = boardCells?[i]
boardCells?[i] = (boardCells?[j])!
boardCells?[j] = w!
i += 1
j -= 1
}
} while (i <= j)
if (l < j) {
sortBoardCells(l,r: j)
}
if (i < r) {
sortBoardCells(i,r: r)
}
}
/**
* By default random seed on filled cells is enabled. This parameter
* affects generating process only. Random seed on
* filled cells causes randomization on filled cells
* within the same impact.
*/
func enableRndSeedOnFilledCells() {
randomizeFilledCells = true
}
/**
* By default random seed on filled cells is enabled. This parameter
* affects generating process only. Lack of random seed on
* filled cells causes no randomization on filled cells
* within the same impact.
*/
func disableRndSeedOnFilledCells() {
randomizeFilledCells = false
}
/**
* Message builder.
* @param msg Message.
*/
private func addMessage(msg: String, msgType: Int) {
let vdt: String = "[" + SudokuStore.JANET_SUDOKU_NAME + "-v." + SudokuStore.JANET_SUDOKU_VERSION + "][" + String(NSDate()) + "]";
var mt: String = "(msg)"
if msgType == MSG_ERROR {
mt = "(error)"
lastErrorMessage = msg
}
messages = messages + SudokuStore.NEW_LINE_SEPARATOR + vdt + mt + " " + msg
lastMessage = msg
}
/**
* Returns list of recorded messages.
* @return List of recorded messages.
*/
func getMessages() -> String {
return messages
}
/**
* Clears list of recorded messages.
*/
func clearMessages() {
messages = ""
}
/**
* Gets last recorded message.
* @return Last recorded message.
*/
func getLastMessage() -> String {
return lastMessage
}
/**
* Gets last recorded error message.
* @return Last recorded message.
*/
func getLastErrorMessage() -> String {
return lastErrorMessage
}
/**
* Return solving time in seconds..
* @return Solving time in seconds.
*/
func getComputingTime() -> Double {
return computingTime
}
/**
* Return current state of the generator
* @return {@link #GENERATOR_INIT_STARTED} or
* {@link #GENERATOR_INIT_FINISHED} or
* {@link #GENERATOR_INIT_FAILED} or
* {@link #GENERATOR_GEN_NOT_STARTED} or
* {@link #GENERATOR_GEN_STARTED} or
* {@link #GENERATOR_GEN_FINISHED} or
* {@link #GENERATOR_GEN_FAILED}.
*/
func getGeneratorState() -> Int {
return generatorState
}
}
|
mit
|
d766bc9751819773e9c21784b02365ba
| 35.776486 | 222 | 0.596452 | 4.252951 | false | false | false | false |
DevAndArtist/swift-functionallayout
|
Sources/Protocols.swift
|
1
|
16700
|
//
// Protocols.swift
// Layout
//
import UIKit
public protocol AssigningInterface {
func assignedTo(_ instance: inout NSLayoutConstraint) -> ActivationInterface
func assignedTo(_ instance: inout NSLayoutConstraint?) -> ActivationInterface
}
public protocol NSLayoutConstraintInterface {
var nsLayoutConstraint: NSLayoutConstraint { get }
}
public protocol AL : NSLayoutConstraintInterface, AssigningInterface {
@discardableResult
func activated() -> NSLayoutConstraintInterface
}
public protocol ActivationInterface : AL {}
// 1
public protocol N : AL {
func named(_ name: String) -> ActivationInterface
}
extension _Constraint : N {
func named(_ name: String) -> ActivationInterface {
let modifiedCopy = self.named(name) as _Constraint
return Constraint(nsLayoutConstraint: modifiedCopy.nsLayoutConstraint)
}
}
public protocol S : AL {
func shouldBeArchived() -> ActivationInterface
}
extension _Constraint : S {
func shouldBeArchived() -> ActivationInterface {
let modifiedCopy = self.shouldBeArchived() as _Constraint
return Constraint(nsLayoutConstraint: modifiedCopy.nsLayoutConstraint)
}
}
public protocol W : AL {
func withPriority(of value: UILayoutPriority) -> ActivationInterface
}
extension _Constraint : W {
func withPriority(of value: UILayoutPriority) -> ActivationInterface {
let modifiedCopy = self.withPriority(of: value) as _Constraint
return Constraint(nsLayoutConstraint: modifiedCopy.nsLayoutConstraint)
}
}
public protocol O : AL {
func offset(by constant: CGFloat) -> ActivationInterface
}
extension _Constraint : O {
func offset(by constant: CGFloat) -> ActivationInterface {
let modifiedCopy = self.offset(by: constant) as _Constraint
return Constraint(nsLayoutConstraint: modifiedCopy.nsLayoutConstraint)
}
}
public protocol M : AL {
func multiplied(with multiplier: CGFloat) -> ActivationInterface
}
extension _Constraint : M {
func multiplied(with multiplier: CGFloat) -> ActivationInterface {
let modifiedCopy = self.multiplied(with: multiplier) as _Constraint
return Constraint(nsLayoutConstraint: modifiedCopy.nsLayoutConstraint)
}
}
// 2
public protocol SN : AL {
func shouldBeArchived() -> N
func named(_ name: String) -> S
}
extension _Constraint : SN {
func shouldBeArchived() -> N {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> S {
return self.named(name) as _Constraint
}
}
public protocol WN : AL {
func withPriority(of value: UILayoutPriority) -> N
func named(_ name: String) -> W
}
extension _Constraint : WN {
func withPriority(of value: UILayoutPriority) -> N {
return self.withPriority(of: value) as _Constraint
}
func named(_ name: String) -> W {
return self.named(name) as _Constraint
}
}
public protocol WS : AL {
func withPriority(of value: UILayoutPriority) -> S
func shouldBeArchived() -> W
}
extension _Constraint : WS {
func withPriority(of value: UILayoutPriority) -> S {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> W {
return self.shouldBeArchived() as _Constraint
}
}
public protocol ON : AL {
func offset(by constant: CGFloat) -> N
func named(_ name: String) -> O
}
extension _Constraint : ON {
func offset(by constant: CGFloat) -> N {
return self.offset(by: constant) as _Constraint
}
func named(_ name: String) -> O {
return self.named(name) as _Constraint
}
}
public protocol OS : AL {
func offset(by constant: CGFloat) -> S
func shouldBeArchived() -> O
}
extension _Constraint : OS {
func offset(by constant: CGFloat) -> S {
return self.offset(by: constant) as _Constraint
}
func shouldBeArchived() -> O {
return self.shouldBeArchived() as _Constraint
}
}
public protocol OW : AL {
func offset(by constant: CGFloat) -> W
func withPriority(of value: UILayoutPriority) -> O
}
extension _Constraint : OW {
func offset(by constant: CGFloat) -> W {
return self.offset(by: constant) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> O {
return self.withPriority(of: value) as _Constraint
}
}
public protocol MW : AL {
func multiplied(with multiplier: CGFloat) -> W
func withPriority(of value: UILayoutPriority) -> M
}
extension _Constraint : MW {
func multiplied(with multiplier: CGFloat) -> W {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> M {
return self.withPriority(of: value) as _Constraint
}
}
public protocol MS : AL {
func multiplied(with multiplier: CGFloat) -> S
func shouldBeArchived() -> M
}
extension _Constraint : MS {
func multiplied(with multiplier: CGFloat) -> S {
return self.multiplied(with: multiplier) as _Constraint
}
func shouldBeArchived() -> M {
return self.shouldBeArchived() as _Constraint
}
}
public protocol MN : AL {
func multiplied(with multiplier: CGFloat) -> N
func named(_ name: String) -> M
}
extension _Constraint : MN {
func multiplied(with multiplier: CGFloat) -> N {
return self.multiplied(with: multiplier) as _Constraint
}
func named(_ name: String) -> M {
return self.named(name) as _Constraint
}
}
public protocol OM : AL {
func offset(by constant: CGFloat) -> M
func multiplied(with multiplier: CGFloat) -> O
}
extension _Constraint : OM {
func offset(by constant: CGFloat) -> M {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> O {
return self.multiplied(with: multiplier) as _Constraint
}
}
// 3
public protocol WSN : AL {
func withPriority(of value: UILayoutPriority) -> SN
func shouldBeArchived() -> WN
func named(_ name: String) -> WS
}
extension _Constraint : WSN {
func withPriority(of value: UILayoutPriority) -> SN {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> WN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> WS {
return self.named(name) as _Constraint
}
}
public protocol OSN : AL {
func offset(by constant: CGFloat) -> SN
func shouldBeArchived() -> ON
func named(_ name: String) -> OS
}
extension _Constraint : OSN {
func offset(by constant: CGFloat) -> SN {
return self.offset(by: constant) as _Constraint
}
func shouldBeArchived() -> ON {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> OS {
return self.named(name) as _Constraint
}
}
public protocol OWN : AL {
func offset(by constant: CGFloat) -> WN
func withPriority(of value: UILayoutPriority) -> ON
func named(_ name: String) -> OW
}
extension _Constraint : OWN {
func offset(by constant: CGFloat) -> WN {
return self.offset(by: constant) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> ON {
return self.withPriority(of: value) as _Constraint
}
func named(_ name: String) -> OW {
return self.named(name) as _Constraint
}
}
public protocol OWS : AL {
func offset(by constant: CGFloat) -> WS
func withPriority(of value: UILayoutPriority) -> OS
func shouldBeArchived() -> OW
}
extension _Constraint : OWS {
func offset(by constant: CGFloat) -> WS {
return self.offset(by: constant) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OS {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> OW {
return self.shouldBeArchived() as _Constraint
}
}
public protocol MWS : AL {
func multiplied(with multiplier: CGFloat) -> WS
func withPriority(of value: UILayoutPriority) -> MS
func shouldBeArchived() -> MW
}
extension _Constraint : MWS {
func multiplied(with multiplier: CGFloat) -> WS {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> MS {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> MW {
return self.shouldBeArchived() as _Constraint
}
}
public protocol MWN : AL {
func multiplied(with multiplier: CGFloat) -> WN
func withPriority(of value: UILayoutPriority) -> MN
func named(_ name: String) -> MW
}
extension _Constraint : MWN {
func multiplied(with multiplier: CGFloat) -> WN {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> MN {
return self.withPriority(of: value) as _Constraint
}
func named(_ name: String) -> MW {
return self.named(name) as _Constraint
}
}
public protocol MSN : AL {
func multiplied(with multiplier: CGFloat) -> SN
func shouldBeArchived() -> MN
func named(_ name: String) -> MS
}
extension _Constraint : MSN {
func multiplied(with multiplier: CGFloat) -> SN {
return self.multiplied(with: multiplier) as _Constraint
}
func shouldBeArchived() -> MN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> MS {
return self.named(name) as _Constraint
}
}
public protocol OMW : AL {
func offset(by constant: CGFloat) -> MW
func multiplied(with multiplier: CGFloat) -> OW
func withPriority(of value: UILayoutPriority) -> OM
}
extension _Constraint : OMW {
func offset(by constant: CGFloat) -> MW {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OW {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OM {
return self.withPriority(of: value) as _Constraint
}
}
public protocol OMN : AL {
func offset(by constant: CGFloat) -> MN
func multiplied(with multiplier: CGFloat) -> ON
func named(_ name: String) -> OM
}
extension _Constraint : OMN {
func offset(by constant: CGFloat) -> MN {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> ON {
return self.multiplied(with: multiplier) as _Constraint
}
func named(_ name: String) -> OM {
return self.named(name) as _Constraint
}
}
public protocol OMS : AL {
func offset(by constant: CGFloat) -> MS
func multiplied(with multiplier: CGFloat) -> OS
func shouldBeArchived() -> OM
}
extension _Constraint : OMS {
func offset(by constant: CGFloat) -> MS {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OS {
return self.multiplied(with: multiplier) as _Constraint
}
func shouldBeArchived() -> OM {
return self.shouldBeArchived() as _Constraint
}
}
// 4
public protocol OWSN : AL {
func offset(by constant: CGFloat) -> WSN
func withPriority(of value: UILayoutPriority) -> OSN
func shouldBeArchived() -> OWN
func named(_ name: String) -> OWS
}
extension _Constraint : OWSN {
func offset(by constant: CGFloat) -> WSN {
return self.offset(by: constant) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OSN {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> OWN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> OWS {
return self.named(name) as _Constraint
}
}
public protocol MWSN : AL {
func multiplied(with multiplier: CGFloat) -> WSN
func withPriority(of value: UILayoutPriority) -> MSN
func shouldBeArchived() -> MWN
func named(_ name: String) -> MWS
}
extension _Constraint : MWSN {
func multiplied(with multiplier: CGFloat) -> WSN {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> MSN {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> MWN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> MWS {
return self.named(name) as _Constraint
}
}
public protocol OMWN : AL {
func offset(by constant: CGFloat) -> MWN
func multiplied(with multiplier: CGFloat) -> OWN
func withPriority(of value: UILayoutPriority) -> OMN
func named(_ name: String) -> OMW
}
extension _Constraint : OMWN {
func offset(by constant: CGFloat) -> MWN {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OWN {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OMN {
return self.withPriority(of: value) as _Constraint
}
func named(_ name: String) -> OMW {
return self.named(name) as _Constraint
}
}
public protocol OMWS : AL {
func offset(by constant: CGFloat) -> MWS
func multiplied(with multiplier: CGFloat) -> OWS
func withPriority(of value: UILayoutPriority) -> OMS
func shouldBeArchived() -> OMW
}
extension _Constraint : OMWS {
func offset(by constant: CGFloat) -> MWS {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OWS {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OMS {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> OMW {
return self.shouldBeArchived() as _Constraint
}
}
public protocol OMSN : AL {
func offset(by constant: CGFloat) -> MSN
func multiplied(with multiplier: CGFloat) -> OSN
func shouldBeArchived() -> OMN
func named(_ name: String) -> OMS
}
extension _Constraint : OMSN {
func offset(by constant: CGFloat) -> MSN {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OSN {
return self.multiplied(with: multiplier) as _Constraint
}
func shouldBeArchived() -> OMN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> OMS {
return self.named(name) as _Constraint
}
}
// 5
public protocol OMWSN : AL {
func offset(by constant: CGFloat) -> MWSN
func multiplied(with multiplier: CGFloat) -> OWSN
func withPriority(of value: UILayoutPriority) -> OMSN
func shouldBeArchived() -> OMWN
func named(_ name: String) -> OMWS
}
extension _Constraint : OMWSN {
func offset(by constant: CGFloat) -> MWSN {
return self.offset(by: constant) as _Constraint
}
func multiplied(with multiplier: CGFloat) -> OWSN {
return self.multiplied(with: multiplier) as _Constraint
}
func withPriority(of value: UILayoutPriority) -> OMSN {
return self.withPriority(of: value) as _Constraint
}
func shouldBeArchived() -> OMWN {
return self.shouldBeArchived() as _Constraint
}
func named(_ name: String) -> OMWS {
return self.named(name) as _Constraint
}
}
|
mit
|
66214cf9dfa74dc3a2159c1523fa639d
| 21.65943 | 81 | 0.606946 | 4.470021 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.